27👍
This works for at least 1.4 and later:
CHOICES = (
('', '-----------'),
('foo', 'Foo')
)
class FooForm(forms.Form):
foo = forms.ChoiceField(choices=CHOICES)
Since ChoiceField is required (by default), it will complain about being empty when first choice is selected and wouldn’t if second.
It’s better to do it like this than the way Yuji Tomita showed, because this way you use Django’s localized validation messages.
6👍
You could validate the field with clean_FOO
CHOICES = (
('------------','-----------'), # first field is invalid.
('Foo', 'Foo')
)
class FooForm(forms.Form):
foo = forms.ChoiceField(choices=CHOICES)
def clean_foo(self):
data = self.cleaned_data.get('foo')
if data == self.fields['foo'].choices[0][0]:
raise forms.ValidationError('This field is required')
return data
If it’s a ModelChoiceField, you can supply the empty_label
argument.
foo = forms.ModelChoiceField(queryset=Foo.objects.all(),
empty_label="-------------")
This will keep the form required, and if -----
is selected, will throw a validation error.
2👍
You can also override form’s __init__()
method and modify the choices
field attribute, reasigning a new list of tuples. (This may be useful for dynamic changes):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['my_field'].choices = [('', '---------')] + self.fields['my_field'].choices
- Python Django Template: Iterate Through List
- Google Oauth2.0 web application's "Authorized redirect URIs" must end with a public top-level domain (such as .com or .org)?
- Daterange on a django-filter
- Facebook, Django, and Google App Engine
- Django – forms.FileField() initial value
-2👍
in argument add null = True
like this
gender = models.CharField(max_length=1, null = True)
http://docs.djangoproject.com/en/dev/ref/models/fields/
for your comment
THEME_CHOICES = (
('--', '-----'),
('DR', 'Domain_registery'),
)
theme = models.CharField(max_length=2, choices=THEME_CHOICES)
- How do I use Django signals with an abstract model?
- SerializerClass field on Serializer save from primary key
- Save image created via PIL to django model
- Python/Django: Which authorize.net library should I use?
- There are errors when I install django by git?