Hedde van der Heide
Hedde van der Heide

Reputation: 22469

Django Forms ChoiceField

I have two questions concerning the Django ChoiceField:

This is my form:

class ContactForm(forms.Form):
   GENDER = (
       (1, _("Mr.")),
       (2, _("Ms.")), 
   )
   prefix = forms.ChoiceField(choices=GENDER)
   ...

This works fine, however I was wondering why the choicefield doesn't take a default..

On the page it renders Mr as the selected value, however if the form is submitted (note: required=True is default for this field) it doesn't throw an error and the value in my form post data is "Ms" instead.

Other question: {{ prefix.get_prefix_display }} doesn't seem to work.. Is there a difference between models and forms with this function's usage?

Upvotes: 5

Views: 19316

Answers (1)

Timmy O'Mahony
Timmy O'Mahony

Reputation: 53998

I think you are mixing up FormFields and ModelFields. Your FormField can set a default choice to appear by using the 'initial' argument:

https://docs.djangoproject.com/en/dev/ref/forms/fields/#initial

but it is represented in your model by a ModelField, for which a default value can be set using 'default' argument:

https://docs.djangoproject.com/en/dev/ref/models/fields/#default

Upvotes: 10

Related Questions