File upload with Django: Invalid form

こ雲淡風輕ζ 提交于 2019-12-22 09:50:43

问题


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.



来源:https://stackoverflow.com/questions/6753087/file-upload-with-django-invalid-form

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