对于web应用程序,以便能够上传文件(资料图片,歌曲,pdf格式,文字......),它通常是很有用的。让我们在这一节中来讨论如何使用django上传文件。
在开始开发图片上传之前,请确保python的图像库(pil)已经安装。现在来说明上传图片,让我们创建一个配置文件格式,在 myapp/forms.py -
# filename : example.py # 九游会下载 copyright : 2020 by nhooo # author by : https://www.elefans.com/biancheng/ # 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 nhooo # author by : https://www.elefans.com/biancheng/ # 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 nhooo # author by : https://www.elefans.com/biancheng/ # 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.save() saved = true else: myprofileform = profileform() return render(request, 'saved.htmll', locals())
这部分不要错过,创建一个profileform 并做了一些修改,添加了第二个参数:request.files. 如果不通过表单验证会失败,给一个消息,说该图片是空的。
现在,我们只需要saved.htmll模板和profile.htmll模板,表单和重定向页面−
myapp/templates/saved.htmll −
# filename : example.py # 九游会下载 copyright : 2020 by nhooo # author by : https://www.elefans.com/biancheng/ # date : 2020-08-08 {% if saved %} your profile was saved. {% endif %} {% if not saved %} your profile was not saved. {% endif %}
myapp/templates/profile.htmll −
# filename : example.py # 九游会下载 copyright : 2020 by nhooo # author by : https://www.elefans.com/biancheng/ # date : 2020-08-08
接下来,我们需要配对网址以开始: myapp/urls.py
# filename : example.py # 九游会下载 copyright : 2020 by nhooo # author by : https://www.elefans.com/biancheng/ # date : 2020-08-08 from django.conf.urls import patterns, url from django.views.generic import templateview urlpatterns = patterns( 'myapp.views', ), )
当访问"/myapp/profile",我们会得到下面 profile.htmll 模板显示 −
在格式提交后,已保存的模板将显示如下 −
这里我们只讲解图片上传示例,但如果想上传其他类型的文件,只需更换 imagefield 在这两个模型及 filefield 表单。