Sorry this is quite late on this thread, but I hadn't noticed any answer for
it.

How about:

from django import forms

class MyNullBooleanField(forms.NullBooleanField):
    def clean(self, value):
        if value is None:
            raise forms.ValidationError('Choose either Yes or No.')
        return super(MyNullBooleanField, self).clean(value)

class YourForm(forms.Form):
    whatever_field_name = MyNullBooleanField()

You could also subclass the django.db.models.fields.NullBooleanField and
overload the formfield method if you want this for free on a ModelForm, but
I suspect we're heading into django-users territory already.

Cheers,
Gary

On Thu, Jun 17, 2010 at 10:39 AM, Matt Hoskins <skaffe...@googlemail.com>wrote:

> My use case is that I want to have a BooleanField on the model and on
> the form want to have the choices of "Unknown", "Yes" and "No" in a
> select list and give a "this field is required" error if the user
> leaves it set to "Unknown" (i.e. require them to actively choose "Yes"
> or "No", rather than defaulting to either of them). I thought I'd just
> be able to use NullBooleanField with "required=True" set, but
> NullBooleanField just ignores the "required" argument. To my mind it
> would be a sensible use of "required" for NullBooleanField, but before
> raising a ticket I thought I'd ask if it was a deliberate oversight or
> if what I'm suggesting isn't sensible for some reason :).
>
> Looking at the code for forms.fields.BooleanField and
> forms.fields.NullBooleanField I guess the change would be in to_python
> in the latter to check in the case where it would return None if
> self.required is true and raise the validation error if that's the
> case (i.e. similar to what BooleanField.to_python does for values of
> False).
>
> Matt
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django developers" group.
> To post to this group, send email to django-develop...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-developers+unsubscr...@googlegroups.com<django-developers%2bunsubscr...@googlegroups.com>
> .
> For more options, visit this group at
> http://groups.google.com/group/django-developers?hl=en.
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django developers" group.
To post to this group, send email to django-develop...@googlegroups.com.
To unsubscribe from this group, send email to 
django-developers+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-developers?hl=en.

Reply via email to