7

I'm creating a form in Django (using ModelForm). There are many checkboxes, and I want to make it so that one of these must be selected in order to submit the form. I don't mean any one checkbox, but one specific box. I can't find anything in the Django documentation. Any help would be appreciated.

3
  • 1
    show your forms. also did required=True not work ? Commented Jun 7, 2013 at 15:50
  • @karthikr Where should the required option go? Commented Jun 7, 2013 at 15:51
  • in the form field definition. docs.djangoproject.com/en/dev/ref/forms/fields/#required Commented Jun 7, 2013 at 15:52

1 Answer 1

11

Something like

from django import forms class MyForm(forms.Form): check = forms.BooleanField(required = True) # your other form fields 

For a BooleanField, required = True will check if the box is checked. This is because data will only be submitted if it is checked.

Source: https://docs.djangoproject.com/en/dev/ref/forms/fields/#django.forms.BooleanField

Validates that the value is True (e.g. the check box is checked) if the field has required=True.

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

2 Comments

how would this be done in the model instead, as my forms.py is just a list of fields to be included from the model, but my model specifies whether a field is allowed to be blank etc.
It seems useless to put a boolean required to be true in a model, but I guess you'd have to override the field's save method to check if it is set to True and raise ValidationError otherwise.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.