CheckBox Input Validation in Django

checkboxdjangovalidation

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

Best Answer

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.