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.
Add template folder in the Django folder and provide its path in django_folder > settings.py. Add file named as urls.py in the app folder and provide its path in django_project > urls.py. Add the function in app_folder > views.py. Provide the URL path in app> urls.py to the functions created in views.py.
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.
form = UploadFileForm(request.POST, request.FILES)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With