Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What am I not doing right in this django file upload form?

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.

like image 955
Geo Avatar asked May 30 '11 19:05

Geo


People also ask

How do I upload and download in Django?

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.


2 Answers

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.

like image 166
Dennis Golomazov Avatar answered Sep 20 '22 14:09

Dennis Golomazov


    form = UploadFileForm(request.POST, request.FILES)
like image 34
Daniel Roseman Avatar answered Sep 19 '22 14:09

Daniel Roseman