What is the method for uploading and displaying images in Django?

The method for uploading and displaying images in Django is as follows:

  1. The file models.py
from django.db import models

class MyModel(models.Model):
    image = models.ImageField(upload_to='images/')  # 设置图片上传的目录,可以根据自己的需求修改
  1. The configuration file named settings.py
  2. The root directory of the media files
  3. The URL for media files.
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
  1. the file that contains the URL patterns
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # 其他URL模式
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
  1. file containing the Python code for handling and processing the logic of a web application
from django.shortcuts import render
from .forms import MyForm

def upload_image(request):
    if request.method == 'POST':
        form = MyForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return render(request, 'success.html')
    else:
        form = MyForm()
    return render(request, 'upload.html', {'form': form})
  1. The file forms.py
from django import forms
from .models import MyModel

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = ['image']
  1. upload the file
<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">上传</button>
</form>
  1. Please provide the image.
<img src="{{ mymodel.image.url }}">

The above is a basic method for uploading and displaying images, which you can modify and expand according to your needs.

bannerAds