Clearing Django form fields when form validation fails?

I have a Django form that allows a user to change their password. I am confused by the form error for fields in which data is still stored.

I tried several methods to remove form.data, but I keep getting the exception message This QueryDict instance is immutable .

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

+7
python django django-forms
source share
7 answers

If you need additional validation using more than one field from a form, override the .clean () method. But if it is for only one field, you can create a clean_field_name () method.

http://docs.djangoproject.com/en/1.1/ref/forms/validation/#ref-forms-validation

0
source share

Regarding the immutable QueryDict error, your problem almost certainly is that you created your instance of the form as follows:

 form = MyForm(request.POST) 

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

 form.data['field'] = None 

is the same as

 request.POST['field'] = None 

To get a form that you can change, you want to build it like this:

 form = MyForm(request.POST.copy()) 
+6
source share

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

 post_vars = {} post_vars.update(request.POST) form = MyForm(post_vars, auto_id='my-form-%s') form.data['fieldname'] = '' form.data['fieldname2'] = '' 
+2
source share

Can't you just remove the password data from the cleaned_data form during validation?

See Django docs for custom validation (especially the second block of code).

0
source share

I just created the form again.

Just try:

 form = AwesomeForm() 

and then draw it.

0
source share

Django has a widget that does this: https://docs.djangoproject.com/en/1.8/ref/forms/widgets/#passwordinput

Now, if you do not work with passwords, you can do something like this:

 class NonceInput(Input): """ Hidden Input that resets its value after invalid data is entered """ input_type = 'hidden' is_hidden = True def render(self, name, value, attrs=None): return super(NonceInput, self).render(name, None, attrs) 

Of course, you can make any django widget forget its value by simply overriding its visualization method (instead of the value that I passed to None in a super call.)

0
source share

I think you need to use JavaScript to hide or remove text from the container.

-2
source share

All Articles