15
votes

I want to add a checkbox to my registration field for terms&use. How can I write a clean method to validate this.

I have written a clean method where I want to be sure that I'm catching checkbox value correctly:

 def clean_terms(self):
         if self.cleaned_data["terms"] == u'on':
             raise forms.ValidationError(
                 "You have to accept terms&conditions to complete registration"
             )

As a result when I fill my registration form and post it, it gives me this validation error :

Terms & Conditions: Select a valid choice. on is not one of the available choices.

So how can I understand that a checkbox is checked and how to correctly implement a term&use checkbox ?

My checkbox field :

 terms = forms.ChoiceField(
     label="Terms&Conditions",
     widget=forms.CheckboxInput()
 )
1
Maybe you should show us how you're defining the checkbox in the first place?Daniel Roseman

1 Answers

23
votes

Don't use a ChoiceField for a single checkbox. Use a BooleanField.

terms = forms.BooleanField(
    error_messages={'required': 'You must accept the terms and conditions'},
    label="Terms&Conditions"
)

You don't even need a clean_ method.