Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clearing Django form fields on form validation error?

I have a Django form that allows a user to change their password. I find it confusing on form error for the fields to have the *'ed out data still in them.

I've tried several methods for removing form.data, but I keep getting a This QueryDict instance is immutable exception message.

Is there a proper way to clear individual form fields or the entire form data set from clean()?

like image 746
Chris W. Avatar asked Mar 01 '10 03:03

Chris W.


2 Answers

Regarding the immutable QueryDict error, your problem is almost certainly that you have created your form instance like this:

form = MyForm(request.POST)

This means that form.data is the actual QueryDict created from the POST vars. Since the request itself is immutable, you get an error when you try to change anything in it. In this case, saying

form.data['field'] = None

is exactly the same thing as

request.POST['field'] = None

To get yourself a form that you can modify, you want to construct it like this:

form = MyForm(request.POST.copy())
like image 159
Ian Clelland Avatar answered Sep 20 '22 21:09

Ian Clelland


Someone showed me how to do this. This method is working for me:

post_vars = {}  
post_vars.update(request.POST)  
form = MyForm(post_vars, auto_id='my-form-%s')  
form.data['fieldname'] = ''  
form.data['fieldname2'] = ''
like image 31
Chris W. Avatar answered Sep 18 '22 21:09

Chris W.