-
-
Save dashdrum/4960474 to your computer and use it in GitHub Desktop.
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 …
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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=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 | |
else: | |
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