form.is_valid()返回文件附件的false

时间:2016-07-28 03:30:23

标签: python django

我有一个要求文件上传的表单页面,但在views.py页面中,form.is_valid()始终返回' False'。以下是forms.py:

forms.py

from django import forms

class Upload_resume(forms.Form):
    f_name = forms.CharField(label='First Name', max_length=64, required=True)
    s_name = forms.CharField(label='Second Name', max_length=64, required=True)
    email = forms.EmailField()
    phone_no = forms.CharField(widget=forms.TextInput(attrs={'type':'number'}))
    resume = forms.Field(label='Upload Resume', widget = forms.FileInput, required = True )

以下是我的views.py

from django.shortcuts import render
from .forms import Upload_resume
from django.core.mail import send_mail, EmailMessage

def up_resume(request):
    if request.method == 'POST':
        for key, value in request.POST.items():
            print(key, value)
        form = Upload_resume(request.POST, request.FILES)
        print form.is_valid()
        print form.errors
        print type(form.errors)

我收到以下错误:

(u'resume', u'NBA Meeting.docx')
(u'f_name', u'Jeril')
(u'phone_no', u'9784644334')
(u's_name', u'K')
(u'csrfmiddlewaretoken', u'9z6I0VaNGESR49iBHXvHwCGRRlGcjH1v')
(u'email', u'jeril.work@gmail.com')
False
<ul class="errorlist"><li>resume<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
<class 'django.forms.utils.ErrorDict'>

可能是什么错误?我上传的文件名称正确显示,但仍然出现错误。有谁可以帮忙。我是Django的新手。

1 个答案:

答案 0 :(得分:2)

POST请求缺少文件。当您尝试上传文件时,模板中的form标记应为enctype='multipart/form-data'