Skip to content

Instantly share code, notes, and snippets.

Forked from davidbgk/
Last active Dec 13, 2015
What would you like to do?
Modified from the original to mirror the functionality provided by the ModelChoiceField. 1. empty_label default is set to u"---------" 2. If there is no initial value for a required field, the empty_label is prepended. What this does is override the ChoiceField's default behavior of using the first value in the choices list if the user makes no …
from django.forms import ChoiceField
''' Based on
modified to mirror the functionality of ModelChoiceField '''
class EmptyChoiceField(ChoiceField):
def __init__(self, choices=(), empty_label=u"---------", required=True, widget=None, label=None,
initial=None, help_text=None, *args, **kwargs):
# prepend an empty label unless the field is required AND
# an initial value is supplied
if required and (initial is not None):
pass # don't prepend the empty label
choices = tuple([(u'', empty_label)] + list(choices))
super(EmptyChoiceField, self).__init__(choices=choices, required=required, widget=widget, label=label,
initial=initial, help_text=help_text, *args, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment