在開始開發(fā)圖片上傳之前,請確保Python的圖像庫(PIL)已經(jīng)安裝?,F(xiàn)在來說明上傳圖片,讓我們創(chuàng)建一個配置文件格式,在 myapp/forms.py -
#-*- coding: utf-8 -*- from django import forms class ProfileForm(forms.Form): name = forms.CharField(max_length = 100) picture = forms.ImageFields()
正如你所看到的,這里的主要區(qū)別僅僅是 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 使用強制性參數(shù):upload_to. 這表示硬盤驅動器,圖像保存所在的地方。注意,該參數(shù)將被添加到 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())
這部分不要錯過,創(chuàng)建一個ProfileForm 并做了一些修改,添加了第二個參數(shù):request.FILES. 如果不通過表單驗證會失敗,給一個消息,說該圖片是空的。
現(xiàn)在,我們只需要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>
接下來,我們需要配對網(wǎng)址以開始: 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 模板顯示 ?
在格式提交后,已保存的模板將顯示如下 ?