English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Django 上传文件

Für Web-Anwendungen, um Dateien hochladen zu können (Bilder, Musik, PDF-Format, Text usw.), ist es oft sehr nützlich. Lassen Sie uns in diesem Abschnitt besprechen, wie man Dateien mit Django hochlädt.

Bild hochladen

Bevor mit der Entwicklung der Bild hochladenden Funktion begonnen wird, stellen Sie sicher, dass die Python-Bibliothek für Bilder (PIL) installiert ist. Lassen Sie uns nun die Bild hochladen erklären und einen Konfigurationsdateiformat erstellen, in myapp/forms.py -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : de.oldtoolbag.com
# Date : 2020-08-08
#-*- coding: utf-8 -*-
 from django import forms
 class ProfileForm(forms.Form):
    name = forms.CharField(max_length= 100)
    picture = forms.ImageFields()

As you can see, the main difference here is just forms.ImageField. The ImageField field ensures that the uploaded file is an image. If not, the format validation will fail.

Now, let's create a "Profile" model to save the uploaded information. In myapp/models.py -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : de.oldtoolbag.com
# Date : 2020-08-08
from django.db import models
 class Profile(models.Model):
    name = models.CharField(max_length= 50)
    picture = models.ImageField(upload_to='pictures')
    class Meta:
       db_table = "profile"

As you can see from the model, the ImageField uses the mandatory parameter: upload_to. This indicates the location on the hard drive where the image is saved. Note that this parameter will be added to the MEDIA_ROOT option defined in the settings.py file.

Now we have the form and the model, let's create the view in myapp/ views.py -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : de.oldtoolbag.com
# Date : 2020-08-08
#-*- coding: utf-8 -*-
 from myapp.forms import ProfileForm
 from myapp.models import Profile
 def SaveProfile(request):
    saved = False
    if request.method == "POST":
       # Get the posted form
       MyProfileForm = ProfileForm(request.POST, request.FILES)
       if MyProfileForm.is_valid():
          profile = Profile()
          profile.name = MyProfileForm.cleaned_data["name"]
          profile.picture = MyProfileForm.cleaned_data["picture"]
          profile.picture = MyProfileForm.cleaned_data["picture"]
          profile.save()
    saved = True
       else:
 
    MyProfileForm = Profileform()

return render(request, 'saved.html', locals())

Diese Teil sollte nicht übersehen werden, ein ProfileForm erstellt und einige Änderungen vorgenommen, um den zweiten Parameter: request.FILES. Wenn die Formularvalidierung nicht erfolgreich ist, wird eine Nachricht angezeigt, dass das Bild leer ist.

myapp/templates/saved.html -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : de.oldtoolbag.com
# Date : 2020-08-08
<html>
    <body>
       {% if saved %}
          <strong>Ihre Profileinstellungen wurden gespeichert.</strong>
       {% endif %}
       {% if not saved %}
          <strong>Ihre Profileinstellungen wurden nicht gespeichert.</strong>
       {% endif %}
    </body>
 </html>

myapp/templates/profile.html -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : de.oldtoolbag.com
# Date : 2020-08-08
<html>
    <body>
       <form name = "form" enctype = "multipart/form-data" 
          action = "{% url "myapp.views.SaveProfile" %}" method = "POST" >{% csrf_token %}
          <div style = "max-width:470px;">
             <center> 
                <input type = "text" style = "margin-links:20%;" 
                placeholder = "Name" name = "name" />
             </center>
          </div>
 
          <br>
          <div style = "max-width:470px;">
             <center> 
                <input type = "file" style = "margin-links:20%;" 
                   placeholder = "Picture" name = "picture" />
             </center>
          </div>
 
          <br>
          <div style = "max-width:470px;">
             <center> 
                <button style = "border:0px;background-color:#4285F4; margin-top:8%; 
                   height:35px; width:80%; margin-links:19"type = "submit" value = "Login">
                   <strong>Login</strong>
                </button>
             </center>
          </div>
       </form>
    </body>
 </html>

接下来,我们需要配对网址以开始: myapp/urls.py

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : de.oldtoolbag.com
# Date : 2020-08-08
from django.conf.urls import patterns, url
 from django.views.generic import TemplateView
 urlpatterns = patterns(
    'myapp.views', url(r'^profile/', TemplateView.as_view(
       template_name = 'profile.htmll'/', 'SaveProfile', name = 'saved')
 )

当访问"/myapp/在 'profile',我们会得到下面 profile.htmll 模板显示 -

在格式提交后,已保存的模板将显示如下 -

在这里,我们只讲解图片上传示例,但如果要上传其他类型的文件,只需更换这两个模型中的 ImageField 和 FileField 表单。