« Link Exchange For Tough Times | Home | Outsourcing Killed By Django And Ruby On Rails »
Clearing Django Form Fields One By One
By Paul Kenjora | December 10, 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.
More from Aware Labs
- Django Generic Relations Made Easier
- Django Deserializer Bug On Foreign Key When None
- Modify Django To Support Binary Order By
- Full Source To Instant RSS Portals Using Django
- Adding Custom Actions To Django Admin Change Forms
Aware Labs Recommends
- An interview with Russell Keith-Magee – Django core contributor (USwaretech)
- Why you should try Django : Agility (Dougal Matthews)
- An Interview with Jacob Kaplan-Moss – Creator of Django (USwaretech)
Topics: Forms, Tutorial | Comments
-
Apple Mac Computers
-
John Parker
-
John Parker
-
williyamb
-
Alex Gaynor
-
Malcolm Tredinnick
-
Foo