Django Aware

« | Home | »

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.

Topics: Forms, Tutorial | Comments

  • i have a method that will take the two parameters which checks for the validity of the user.if such is a case what should be used ie, an abstract class or an interface for the method
  • John Parker
  • John Parker
    I agree with what you have to say.....
  • williyamb
    Ecommerce Web Design Ecommerce Web Design
  • I'd just create a custom widget with a render_value kwarg like the password widget does:

    http://code.djangoproject.com/browser/django/tr...
  • Now, my intuition arguably works differently from others, but I'd argue that this approach is slightly backwards. It certainly works and I can't see it ever failing, but on some level it's coupling input to output more than you might prefer. Altering the submitted data is the wrong end of the pipeline. The end goal is never to render that piece of data, which is a property of the form.

    I'll eventually write this up for the docs (or you could beat me to it and submit a patch), but here's my preferred approach to this kind of problem: http://groups.google.com/group/django-users/bro...
  • Foo
    And self.data['some_field'] is an instance variable in what class?
blog comments powered by Disqus