English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
对于Web应用程序,以便能够上传文件(资料图片,歌曲,PDF格式,文字……),它通常是很有用的。让我们在这一节中来讨论如何使用Django上传文件。
在开始开发图片上传之前,请确保Python的图像库(PIL)已经安装。现在来说明上传图片,让我们创建一个配置文件格式,在 myapp/forms.py -
# Nome del File: example.py # Copyright: 2020 Da w3codebox # Autore: it.oldtoolbag.com # Data: 2020-08-08 #-*- coding: utf-8 -*- from django import forms class ProfileForm(forms.Form): name = forms.CharField(max_length=100) picture = forms.ImageFields()
正如你所看到的,这里的主要区别仅仅是 forms.ImageField。ImageField字段将确保上传的文件是一个图像。如果不是,格式验证将失败。
现在,让我们创建一个 "Profile" 模型,以保存上传的资料。在 myapp/models.py -
# Nome del File: example.py # Copyright: 2020 Da w3codebox # Autore: it.oldtoolbag.com # Data: 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"
正如所看到的模型,ImageField 使用强制性参数:upload_to. 这表示硬盘驱动器,图像保存所在的地方。注意,该参数将被添加到 settings.py文件中定义的MEDIA_ROOT选项。
现在我们有表单和模型,让我们来创建视图,在 myapp/views.py -
# Nome del File: example.py # Copyright: 2020 Da w3codebox # Autore: it.oldtoolbag.com # Data: 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.save() saved = True else: MyProfileForm = Profileform() return render(request, 'saved.htmll', locals())
Non perdetevi questa parte, create un ProfileForm e apportate alcune modifiche, aggiungendo il secondo parametro: request.FILES. Se il modulo non passa la validazione fallirà, fornite un messaggio che dice che l'immagine è vuota.
Ora, ci servono solo i template saved.htmll e profile.htmll, il modulo e la pagina di reindirizzamento−
myapp/templates/saved.htmll −
# Nome del File: example.py # Copyright: 2020 Da w3codebox # Autore: it.oldtoolbag.com # Data: 2020-08-08 <html> <body> {% if saved %} <strong>Il tuo profilo è stato salvato.</strong> {% endif %} {% if not saved %} <strong>Il tuo profilo non è stato salvato.</strong> {% endif %} </body> </html>
myapp/templates/profile.htmll −
# Nome del File: example.py # Copyright: 2020 Da w3codebox # Autore: it.oldtoolbag.com # Data: 2020-08-08 <html> <body> <form nome="form" enctype="multipart/form-data" azione="{% url "myapp.views.SaveProfile" %}" metodo="POST" {% csrf_token %} <div style="larghezza massima:470px;"> <center> <input type="testo" style="margine sinistro:20%;" seleziona placeholder="Nome" nome="nome"/> </center> </div> <br> <div style="larghezza massima:470px;"> <center> <input type="file" style="margine sinistro:20%;" seleziona placeholder="Immagine" nome="immagine"/> </center> </div> <br> <div style="larghezza massima:470px;"> <center> <button style="bordo:0px; colore di sfondo:#4285F4; margine superiore:8%; altezza:35px; larghezza:80%; margine sinistro:19%;" tipo="submit" valore="Login" <strong>Login</strong> </button> </center> </div> </form> </body> </html>
Quindi, dobbiamo abbinare gli URL per iniziare: myapp/urls.py
# Nome del File: example.py # Copyright: 2020 Da w3codebox # Autore: it.oldtoolbag.com # Data: 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', url(r'^saved/', 'SaveProfile', name='saved') )
Quando si accede a "/myapp/profile", otterremo il seguente template profile.htmll mostrato −
Dopo la formattazione del submit, il template salvato sarà visualizzato come segue −
In questo esempio, parleremo solo della gestione dell'upload delle immagini, ma se si desidera caricare altri tipi di file, è sufficiente sostituire ImageField in questi due modelli e FileField nel form.