Created
April 29, 2013 12:21
-
-
Save mounirmesselmeni/5481285 to your computer and use it in GitHub Desktop.
Add an empty choice to a required Django ChoiceField
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 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