Chris W.
Chris W.

Reputation: 655

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()?

Upvotes: 7

Views: 13422

Answers (7)

Chris W.
Chris W.

Reputation: 655

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'] = ''

Upvotes: 2

Visgean Skeloru
Visgean Skeloru

Reputation: 2263

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

now if you are not working 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 just by overriding its render method (instead of value I passed None in super call.)

Upvotes: 0

Farhan Hafeez
Farhan Hafeez

Reputation: 644

I just created the form again.

Just try:

form = AwesomeForm()

and then render it.

Upvotes: 0

Ian Clelland
Ian Clelland

Reputation: 44152

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())

Upvotes: 7

Mathieu Dhondt
Mathieu Dhondt

Reputation: 8914

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

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

Upvotes: -1

piyer
piyer

Reputation: 746

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

Upvotes: -2

Igor Sobreira
Igor Sobreira

Reputation: 177

If you need extra validation using more than one field from a form, override the .clean() method. But if it's just for one field, you can create a clean_field_name() method.

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

Upvotes: 0

Related Questions