Clearing Django Form Fields One By One
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.
More from Aware Labs
- Everything A Django Developer Needs To Create Logins
- Goodbye WebFaction Django Hosting – A Reflection
- Django Generic Relations Made Easier
- Django Deserializer Bug On Foreign Key When None
- Modify Django To Support Binary Order By
Aware Labs Recommends
- Popularizing Django — Or Reusable apps considered harmful. (USwaretech)
- An Interview with Jacob Kaplan-Moss – Creator of Django (USwaretech)
- Django’s tipping point (Antonio Cangiano)
-
Apple Mac Computers
-
John Parker
-
John Parker
-
williyamb
-
Alex Gaynor
-
Malcolm Tredinnick
-
Foo

![Recommend [AwareLabs]](http://s3.amazonaws.com/arkayne-media/img/badge/logo-recommend-badge-medium.png)