在开始开发图片上传之前,请确保python的图像库(pil)已经安装。现在来说明上传图片,让我们创建一个配置文件格式,在 myapp/forms.py -
#-*- coding: utf-8 -*- from django import forms class profileform(forms.form): name = forms.charfield(max_length = 100) picture = forms.imagefields()
正如你所看到的,这里的主要区别仅仅是 forms.imagefield。imagefield字段将确保上传的文件是一个图像。如果不是,格式验证将失败。
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选项。
#-*- 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 −
<html> <body> {% if saved %} <strong>your profile was saved.</strong> {% endif %} {% if not saved %} <strong>your profile was not saved.</strong> {% endif %} </body> </html>
myapp/templates/profile.htmll −
<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-left:20%;" placeholder = "name" name = "name" /> </center> </div> <br> <div style = "max-width:470px;"> <center> <input type = "file" style = "margin-left: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-left:19%;" type = "submit" value = "login" > <strong>login</strong> </button> </center> </div> </form> </body> </html>
接下来,我们需要配对网址以开始: myapp/urls.py
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') )
当访问"/myapp/profile",我们会得到下面 profile.htmll 模板显示 −
在格式提交后,已保存的模板将显示如下 −