Confirm / clear FileField in non-modeled form in Django?

I end up trying to check FileField for extension type. But I am having problems even getting a clean method for this field to get 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 get the following output:

 clean_file value: None form is valid 

In other words, the clean_file method cannot get the file data. Similarly, if it returns None, the form remains valid.

Here is my html form:

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

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

+4
source share
1 answer

You do not submit request.FILES to the form when you instantiate the message.

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

See the documentation .

Also note that you create the form twice in POST, which is optional. Transfer the first to the else clause at the end of the function (at the same level as if request.method == 'POST' ).

+4
source

All Articles