Why does my Django form keep saying “this field is required”

[亡魂溺海] 提交于 2020-07-09 09:30:06

问题


Does anyone know why my form (filepicker) is constantly returning "this field is required" when it worked in a simpler version?

My view is

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

My Model is

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)

And my form is

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

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

The error prints out as

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


回答1:


Adding my comment as a proper answer:

Please try adding enctype= multipart/form-data to your <form> element in your template file.

If you don't have this element your request.FILES will always be empty.

Copying from 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.




回答2:


If the field is required in your models.py (i.e. you have not stated blank=True or null=True), and you are using a ModelForm, then that will be a required field in your ModelForm



来源:https://stackoverflow.com/questions/28841054/why-does-my-django-form-keep-saying-this-field-is-required

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!