Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate/clean a FileField on a non-model form in Django?

I'm ultimately trying to validate a FileField by extension type. But I'm having trouble even getting the clean method for this field to pickup the POSTed value.

from django.forms.forms import Form
from django.forms.fields import FileField
from django.forms.util import ValidationError

class TestForm(Form):        
    file = FileField(required=False)

    def clean_file(self):
        value = self.cleaned_data["file"]
        print "clean_file value: %s" % value
        return None     

@localhost
def test_forms(request):
    form = TestForm()    
    if request.method == "POST":
        form = TestForm(request.POST)        
        if form.is_valid():
            print "form is valid"
    return render_to_response("test/form.html", RequestContext(request, locals()))

When I run the code, I'm getting the following output:

clean_file value: None
form is valid

In other words, the clean_file method is not able to get the file data. Likewise, if it returns None, the form is still valid.

Here is my form html:

<form enctype="multipart/form-data" method="post" action="#">
   <input type="file" id="id_file" name="file">
   <input type="submit" value="Save">
</form>

I have seen a couple snippets with solutions for this problem, but I cannot get them to work with a non-model form. They both declare a custom field type. When I do that, I get the same problem; calling super() returns a None object.

like image 398
Chase Seibert Avatar asked Oct 07 '10 17:10

Chase Seibert


1 Answers

You're not passing request.FILES into the form when you instantiate it in the post.

 form = TestForm(request.POST, request.FILES)

See the documentation.

Also note that you're instantiating the form twice on POST, which is unnecessary. Move the first one into an else clause at the end of the function (at the same level as if request.method == 'POST').

like image 76
Daniel Roseman Avatar answered Sep 28 '22 10:09

Daniel Roseman