Skip to content

Instantly share code, notes, and snippets.

@Gautier
Created May 19, 2011 12:01
Show Gist options
  • Save Gautier/980597 to your computer and use it in GitHub Desktop.
Save Gautier/980597 to your computer and use it in GitHub Desktop.
Yes No boolean field for
from django import forms
class YesNoNullBooleanSelect(forms.Select):
"""
A Select Widget intended to be used with YesNoBooleanField.
"""
def value_from_datadict(self, data, files, name):
value = data.get(name, None)
return {u'2': True,
True: True,
'True': True,
'yes': True,
u'3': False,
'False': False,
'no': False,
False: False}.get(value, None)
class YesNoBooleanField(forms.NullBooleanField):
"""
A field whose valid values are None, True and False. Invalid values are
cleaned to None.
"""
widget = YesNoNullBooleanSelect
def to_python(self, value):
if value in (True, 'True', '1', 'yes'):
return True
elif value in (False, 'False', '0', 'no'):
return False
else:
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment