在開始開發圖片上傳之前,請確保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 模板顯示 ?
在格式提交後,已儲存的模板將顯示如下 ?