Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CheckBox Input Validation in Django

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()
 )
like image 260
iva123 Avatar asked Oct 19 '11 15:10

iva123


Video Answer


1 Answers

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.

like image 93
Daniel Roseman Avatar answered Oct 05 '22 16:10

Daniel Roseman