Skip to content

Instantly share code, notes, and snippets.

@mounirmesselmeni
Created April 29, 2013 12:21
Show Gist options
  • Save mounirmesselmeni/5481285 to your computer and use it in GitHub Desktop.
Save mounirmesselmeni/5481285 to your computer and use it in GitHub Desktop.
Add an empty choice to a required Django ChoiceField
from django import forms
from django.core.exceptions import ValidationError
class EmptyChoiceField(forms.ChoiceField):
def __init__(self, choices=(), empty_label=None, required=True, widget=None, label=None,
initial=None, help_text=None, *args, **kwargs):
if required and empty_label is not None:
choices = tuple([(0, empty_label)] + list(choices))
super(EmptyChoiceField, self).__init__(choices=choices, required=required, widget=widget, label=label,
initial=initial, help_text=help_text, *args, **kwargs)
def validate(self, value):
if value == "0":
raise ValidationError(self.error_messages['required'])
super(EmptyChoiceField, self).validate(value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment