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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With