django - 为什么我的 Django 表单一直显示 "this field is required"

标签 django django-forms

有谁知道为什么我的表单(文件选择器)在更简单的版本中工作时不断返回“此字段是必需的”?

我的观点是

def add_attempt(request, m_id, a_id):
    template = loader.get_template('add_attempt.html')
    if request.method == 'POST':
        import pprint 
        pprint.pprint(request.POST)
        pprint.pprint(request.FILES)
        form = UploadAttemptForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            form.instance.pub_date = datetime.datetime.now()
            form.instance.user_id = request.user
            form.instance.assignment = m.Assignment.objects.get(id=a_id)
            form.save()
            return HttpResponseRedirect(reverse('assignment', args=(m_id, a_id)))
        else:
            print form.errors
    else:
        form = UploadAttemptForm()
    context = RequestContext(request, 
        {
        'form':form,
        })
    return HttpResponse(template.render(context))

我的模型是

class Attempt(models.Model):
    user_id = models.ForeignKey(User)
    pdf_filename = models.FileField(storage=settings.S3_STORAGE, upload_to='pdfs')
    pub_date = models.DateTimeField('date uploaded')
    assignment = models.ForeignKey(Assignment)

我的表格是

class UploadAttemptForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(UploadAttemptForm, self).__init__(*args, **kwargs)

    class Meta():
        model = Attempt
        fields = ['pdf_filename',]

错误打印为

`<QueryDict: {u'submit': [u'Upload Attempt'], u'pdf_filename': [u'something.pdf']}>`

<MultiValueDict: {}> <ul class="errorlist"><li>pdf_filename<ul class="errorlist"><li>This field is required.</li></ul></li></ul>

最佳答案

添加我的评论作为正确答案:

请尝试添加 enctype= multipart/form-data给你的<form>模板文件中的元素。

如果你没有这个元素你的request.FILES永远是空的。

复制自 https://docs.djangoproject.com/en/1.7/topics/http/file-uploads/#basic-file-uploads :

Note that request.FILES will only contain data if the request method was POST and the <form> that posted the request has the attribute enctype="multipart/form-data". Otherwise, request.FILES will be empty.

关于django - 为什么我的 Django 表单一直显示 "this field is required",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28841054/

相关文章:

python - django模型的对象声明在哪里?

django - 设置 Django ModelChoiceField 的初始值

django-forms - 带有动态定义字段的 Django Crispy Form

python - 为 django 密码重置表单添加样式

javascript - 在 Django url 模板标签中获取 javascript 变量的值

python - Django上传文件的正确访问器

python - 使用 django-social-auth 出现导入错误

python - Django SMTPAuthenticationError

html - 如何将 html 表单转换为 Django 表单并保留样式?

python - Django 表单 - 设置标签