开发者

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 instan开发者_开发知识库ce is immutable exception message.

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


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


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


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


I just created the form again.

Just try:

form = AwesomeForm()

and then render it.


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜