15

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? Commented Oct 19, 2011 at 15:18

1 Answer 1

23

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.