File upload with Django: Invalid form

2019-05-18 21:33发布

问题:

First time posting a question. I've basically copied everything I've found on here and on the django documentation site and I can't figure out what I'm doing incorrectly

Here is the code from my views.py file

from django import forms

class UploadFileForm(forms.Form):
    title = forms.CharField(max_length=50)
    file  = forms.FileField()

def upload_file(request):   
    form = UploadFileForm(request.POST, request.FILES)
    if form.is_valid():
        response = "Form is valid."              
    else:
        response = "Failed to upload attachment."
    return HttpResponse(response)

And my html file:

 <form name="attachmentForm" action="http://mysite.com/uploadattachments" enctype="multipart/form-data" method="post">
      <p>
    Please specify a file, or a set of files:<br/>
    <input id="attachment" type="file" name="datafile" size="40"/>
      </p>
      <input type="submit" value="Send"/>
    </form>

When I test it out I get "Failed to upload attachment". Is there anything obvious that I'm missing here? I'm a bit new to django as well so I apologize if it's just a dumb error. Thanks in advance!

回答1:

Not entirely sure on this, but I would guess that since you've named your form fields file and title in the definition of the UploadFileForm class, the name attribute of your form fields in the html has to match that, i.e. the file upload field has to be named "file", and there also has to be a "title" field.

I'd recommend checking out https://docs.djangoproject.com/en/dev/topics/forms/ where there are examples on how to render the form automatically, or semi-automatically. Once you have it working with the automatically rendered form, you can customize it to your needs.