Skip to content

Clearing Django Form Fields One By One

by Paul Kenjora on December 10th, 2008

I just spent an hour looking all over the web for something everyone assumes everyone else already knows. If you’re new to Django and you’re trying to clear a form field on validation then the solution is not intuitive.

Take a common scenario, you have a CAPTACHA image and the user enters it incorrectly, next time around you want to clear it and show an error, the rest of the form should be preserved. How do you clear a Django form field?

Wrong: Create a new form and copy the data across. This is not only overly complex, prone to error, and generally poorly readable code, its too much work. Don’t do it!

Correct: When populating the form from request.POST or request.GET make a copy of it and then clear the data attribute for that field. Here is an example:

The secret sauce is self.data['some_field'] = ”. The form itself does not contain any data, so trying to dig through the form attributes to clear a field is a dead end. If you do dig down deep enough, you will find that the form calls a widget method that goes to whatever data was associated with the form and fetches it. Hence clearing the data attribute works!

This makes sense to developers who’ve been around Django and its methodologies for some time. For novices the intuitive approach is to manipulate the form. Hope this gets picked up by enough searches to save others some time.

From → Forms, Tutorial

blog comments powered by Disqus