目录

Django - 文件上传( File Uploading)

通常,网络应用程序能够上传文件(个人资料图片,歌曲,PDF格式,单词.....)非常有用。 我们将在本章讨论如何上传文件。

上传图片

在开始播放图像之前,请确保已安装Python Image Library(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将确保上传的文件是图像。 如果没有,表单验证将失败。

现在让我们创建一个“配置文件”模型来保存我们上传的个人资料。 这是在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选项中。

现在我们有了Form和Model,让我们在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.html', locals())

不容错过的部分是,创建ProfileForm时有一个变化,我们添加了第二个参数: request.FILES 。 如果未通过,则表单验证将失败,并显示一条消息,指出图片为空。

现在,我们只需要saved.html模板和profile.html模板,用于表单和重定向页面 -

myapp/templates/saved.html -

<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.html -

<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>

接下来,我们需要启动这对URL: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.html')), url(r'^saved/', 'SaveProfile', name = 'saved')
)

访问“/ myapp/profile”时,我们将呈现以下profile.html模板 -

正在上传图片

在表单帖子上,将呈现保存的模板 -

表格帖子模板

我们有一个图像样本,但是如果你想上传另一种类型的文件,而不仅仅是图像,只需用ImageField替换Model和Form中的FileField

↑回到顶部↑
WIKI教程 @2018