Skip to content

Instantly share code, notes, and snippets.

@dashdrum
Created November 12, 2016 15:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dashdrum/60408bde2e096edc3159782f509b90bb to your computer and use it in GitHub Desktop.
Save dashdrum/60408bde2e096edc3159782f509b90bb to your computer and use it in GitHub Desktop.
from __future__ import unicode_literals
from django.forms import ChoiceField
''' Based on https://gist.github.com/davidbgk/651080
modified to mirror the functionality of ModelChoiceField '''
class EmptyChoiceField(ChoiceField):
def __init__(self, choices=(), empty_label="---------", 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
else:
choices = tuple([('', 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