开发者

Django Forms ChoiceField

开发者 https://www.devze.com 2023-04-11 10:29 出处:网络
I have two questions concerning the Django ChoiceField: This is my form: class ContactForm(forms.Form):

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 b开发者_开发问答etween models and forms with this function's usage?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号