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.
1 Answer
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.
2 Comments
holmeswatson
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.
Mark
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.
required=Truenot work ?requiredoption go?