Reputation: 96897
This is my form:
from django import forms
class UploadFileForm(forms.Form):
titl = forms.CharField(max_length=50)
ffile = forms.FileField()
This is my views.py file:
def handle_uploaded_file(file_path):
print "handle_uploaded_file"
dest = open(file_path.name,"wb")
for chunk in file_path.chunks():
dest.write(chunk)
dest.close()
def handle_upload(request):
c = {}
c.update(csrf(request))
if request.method == "POST":
form = UploadFileForm(request.POST)
if form.is_valid():
handle_uploaded_file(request.FILES["ffile"])
return HttpResponseRedirect("/thanks")
else:
form = UploadFileForm()
c.update({"form":form})
return render_to_response("upload.html",c)
And this is the content of upload.html:
<form enctype="multipart/form-data" method="post" action="/handle_upload/">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Upload it"/>
</form>
Whenever I try to submit the form, I get a "This field is required" for the ffile
field. What am I doing wrong? Just to mention, I am uploading a file each time.
Upvotes: 15
Views: 6779
Reputation: 1919
If you have included request.FILES
and added the enctype="multipart/form-data"
, but are still seeing this error, it could be you are not declaring the <input>
correctly.
For example, if explicitly declare the input html in your template like:
<input type="file" value="Upload CSV File" />
You may not be passing the expected input id or name attributes of the input form element.
Be sure that your template is using the form element tag, i.e. {{ form.file }}
,
which django will then render as: <input id="id_file" name="file" type="file" required="">
on the page.
Upvotes: 0
Reputation: 17349
Just for future reference. I had the same error, though I included request.FILES
in form initialization. The problem was in the template: I forgot to add enctype="multipart/form-data"
attribute to the <form>
tag.
Upvotes: 43