views:

52

answers:

1

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.

+1  A: 

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').

Daniel Roseman