Detailed Explanation of Uploading and Displaying Pictures by Django

  • 2021-07-22 10:50:23
  • OfStack

Chapter 1 New Project and Creating app

New projects and create app do not have to post out, I here is the test picture upload function can be achieved, so the project is new, normal in some app can be

Chapter 2 Model Layer:

2.1 Create a database


from django.dbimport models

# Create your models here.
class User(models.Model):
  name= models.CharField(max_length=50)
  # upload_to  Specify the upload file location 
  #  This specifies the storage in the img/  Directory 
  headimg = models.FileField(upload_to="img/")

  #  Return name 
  def__str__(self):
    returnself.name

2.2 Initialize the database:


(mypy3) ➜ BBS python manage.py makemigrations

Migrations for 'app01':

 app01/migrations/0001_initial.py

  - Create model User

(mypy3) ➜ BBS python manage.py migrate    

Operations to perform:

 Apply all migrations: admin, app01, auth, contenttypes, sessions

Chapter 3 Modifying the Configuration File

3.1 Add the following configuration to settings:


MEDIA_ROOT= os.path.join(BASE_DIR, 'media').replace("\\", "/")
MEDIA_URL = '/media/'

3.2 urls file for the project:


from django.conf.urlsimport url
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
  url(r'^admin/', admin.site.urls),
  # url(r'^regsiter/', views.regsiter),
  # url(r'', TemplateView.as_view(template_name="app01/index.html")),
  path('app01/', include('app01.urls'))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

3.3 app:


from django.urlsimport path
from . import views

app_name = 'app01'
urlpatterns = [
  path('add/', views.add, name='add'),
  # path('index/', views.index, name='index'),
]

3.4 Modify template configuration:


TEMPLATES= [
  {
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [os.path.join(BASE_DIR, 'templates')],
    'APP_DIRS': True,
    'OPTIONS': {
      'context_processors': [
        'django.template.context_processors.debug',
        'django.template.context_processors.request',
        'django.contrib.auth.context_processors.auth',
        'django.contrib.messages.context_processors.messages',
      ],
    },
  },
]

Chapter 4 Data Verification Module:

If the data needs to be verified, if you don't want to verify, this can be ignored

4.1 Create an forms file under app:


from django import forms

#  Form classes are used to generate forms 
class AddForm(forms.Form):
  name = forms.CharField()
  headimg = forms.FileField()

Chapter 5 View Layer:

5.1 Writing Image Processing Logic


from django.shortcutsimport render
from .models import User
from .forms import AddForm

# Create your views here.
def add(request):
  #  Determine whether it is post  Method submission 
  ifrequest.method == "POST":
    af = AddForm(request.POST, request.FILES)
    #  Determine whether the form value is in line with the method 
    ifaf.is_valid():
      name = af.cleaned_data['name']
      headimg = af.cleaned_data['headimg']
      user = User(name=name, headimg=headimg)
      user.save()
      returnrender(request, 'app01/index.html', context={"user":user})
  else:
    af = AddForm()
    returnrender(request, 'app01/add.html', context={"af":af})

Chapter 6 Template Layer:

Uploaded html


<!-- templates/users/add.html -->
<!doctype html>
<html>
<head>
  <title>Add</title>
  <meta charset="utf-8">
</head>
<body>
  <h1>Add!</h1>

  <form method="post" enctype="multipart/form-data" action="{% url'app01:add' %}">
    {%csrf_token %}
    {{ af.as_p }}
    <inputtype="submit" value="OK"/>
  </form>
</body>
</html>

Viewed html


<!-- templates/users/index.html -->
<!doctype html>
<html>
<head>
  <title>Detail</title>
  <meta charset="utf-8">
</head>
<body>
  <p>{{user.name}}</p>
  <img width="50%" height="50%"src="/media/{{ user.headimg }}">
</body>
</html>

Related articles: