Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Forms ChoiceField

Tags:

forms

django

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?

like image 403
Hedde van der Heide Avatar asked Oct 05 '11 11:10

Hedde van der Heide


People also ask

How do you define choice fields in Django?

Choices can be any sequence object – not necessarily a list or tuple. The first element in each tuple is the actual value to be set on the model, and the second element is the human-readable name. Let us create a choices field with above semester in our django project named geeksforgeeks.

How do I select a field in Django?

ChoiceField in Django Forms is a string field, for selecting a particular choice out of a list of available choices. It is used to implement State, Countries etc. like fields for which information is already defined and user has to choose one. It is used for taking text inputs from the user.


1 Answers

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

like image 100
Timmy O'Mahony Avatar answered Oct 06 '22 00:10

Timmy O'Mahony