[Answered ]-Reset checkbox in Django

2👍

✅

You should override UserForm.clean() method:

class UserForm(forms.ModelForm, TOUSetPasswordMixin):    

    def clean(self):
        super(UserForm, self).clean()
        if self.errors:
            self.data = self.data.copy()
            self.data['accept_tou'] = ''

0👍

You can define clean_FIELD_NAME() methods which can validate and alter data, as documented here:

https://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-a-specific-field-attribute

or use this:

https://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other

Without any sample code in your question. I can’t give you an example.

0👍

I did it!

Thanks to all of you, especially to @catavaran.

I just changed value in wrong dictionary.
This works.

class TOUMixin(forms.Form):
    error_messages = {
        'accept_tou': _("You must read and accept tou"),
    }
    accept_tou = forms.BooleanField(label=_('I have read and accept tou'), initial=False, required=False)

    def clean_accept_tou(self):
        value = self.cleaned_data.get('accept_tou')
        if not value:
            raise forms.ValidationError(
                self.error_messages['accept_tou'],
                code='accept_tou',
            )
        return value

    def is_valid(self):
        result = super(TOUMixin, self).is_valid()
        if not result:
            self.data.pop('accept_tou', None)
        return result

Leave a comment