mpen
mpen

Reputation: 282865

Required boolean field?

I've got a boolean field,

is_operable = BooleanField(widget=RadioSelect(choices=YES_OR_NO, renderer=InlineRadioFieldRenderer), required=False, initial=True)

Which is rendered as two radio buttons (yes or no), but I want it to be required. The problem is that if I change it to required=True, it throws a validation error when it gets False.

Is there a way around this?


YES_OR_NO = (
    (True, 'Yes'),
    (False, 'No')
)

Upvotes: 4

Views: 4828

Answers (2)

Mark Lavin
Mark Lavin

Reputation: 25164

I would recommend using a TypedChoiceField which coerces the choices YES_OR_NO into a boolean. See the docs: http://docs.djangoproject.com/en/1.2/ref/forms/fields/#django.forms.TypedChoiceField

Upvotes: 3

Steve Jalim
Steve Jalim

Reputation: 12195

Leave it as required=False and write a custom clean_is_operable method that checks that you've got what you want, else throws a ValidationError or the like

Upvotes: 3

Related Questions