English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Pour une application web, il est souvent utile de pouvoir envoyer des fichiers (images, chansons, format PDF, texte...). Dans cette section, nous discuterons de la manière d'utiliser Django pour envoyer des fichiers.
Avant de commencer à développer l'envoi d'images, assurez-vous que la bibliothèque d'images Python (PIL) est installée. Expliquons maintenant l'envoi d'images, créons un fichier de configuration pour myapp/forms.py -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : fr.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()
正如你所看到的,这里的主要区别仅仅是 forms.ImageField。ImageField字段将确保上传的文件是一个图像。如果不是,格式验证将失败。
现在,让我们创建一个 "Profile" 模型,以保存上传的资料。在 myapp/models.py -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : fr.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"
正如所看到的模型,ImageField 使用强制性参数:upload_to. 这表示硬盘驱动器,图像保存所在的地方。注意,该参数将被添加到 settings.py文件中定义的MEDIA_ROOT选项。
现在我们有表单和模型,让我们来创建视图,在 myapp/ views.py -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : fr.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())
Ne manquez pas cette partie, créez un ProfileForm et apportez quelques modifications, ajoutez un deuxième paramètre : request.FILES. Si la validation du formulaire échoue, donnez un message en disant que l'image est vide.
myapp/templates/saved.html -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : fr.oldtoolbag.com # Date : 2020-08-08 <html> <body> {% if saved %} <strong>Votre profil a été sauvegardé.</strong> {% endif %} {% if not saved %} <strong>Votre profil n'a pas été sauvegardé.</strong> {% endif %} </body> </html>
myapp/templates/profile.html -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : fr.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-gauche:20%;" placeholder = "Name" name = "name" /> </center> </div> <br> <div style = "max-width:470px;"> <center> <input type = "file" style = "margin-gauche: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-gauche:19"type = "submit" value = "Login"> <strong>Connexion</strong> </button> </center> </div> </form> </body> </html>
接下来,我们需要配对网址以开始: myapp/urls.py
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : fr.oldtoolbag.com # Date : 2020-08-08 from django.conf.urls import patterns, url / template_name = 'profile.htmll')), url(r'^saved/', 'SaveProfile', name = 'saved') )
当访问/myapp/在 'profile',我们会得到下面 profile.htmll 模板显示 -
在格式提交后,已保存的模板将显示如下 -
我们在这里只讲解图片上传示例,但如果想上传其他类型的文件,只需更换 ImageField 在这两个模型及 FileField 表单。