Django上傳檔

對於Web應用程式,以便能夠上傳檔(資料圖片,歌曲,PDF格式,文字......),它通常是很有用的。讓我們在這一節中來討論如何使用Django上傳檔。

上傳圖片

在開始開發圖片上傳之前,請確保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字段將確保上傳的檔是一個圖像。如果不是,格式驗證將失敗。

現在,讓我們創建一個 “Profile” 模型,以保存上傳的資料。在 myapp/models.py -
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 -
#-*- 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 範本顯示 −

在格式提交後,已保存的範本將顯示如下 −

這裏我們只講解圖片上傳示例,但如果想上傳其他類型的檔,只需更換 ImageField 在這兩個模型及 FileField 表單。


上一篇: Django表單處理 下一篇: Django Apache配置