How do I make a Django ModelForm menu item selected by default?

你离开我真会死。 提交于 2019-12-21 03:56:20

问题


I am working on a Django app. One of my models, "User", includes a "gender" field, as defined below:

GENDER_CHOICES = (
        ('M', 'Male'),
        ('F', 'Female'),
    )
gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True)

I am using a ModelForm to generate a "new user" HTML form. My Google-fu seems to be failing me -- how can I make this HTML form have the "Male" item selected by default in the drop-down box? (i.e. so selected="selected" for this item.)


回答1:


If you need a blank form with a default value selected, then pass an 'initial' dictionary to the constructor of your model form using the name of your field as the key:

form = MyModelForm (initial={'gender':'M'})

-OR-

You can override certain attributes of a ModelForm using the declarative nature of the Forms API. However, this is probably a little cumbersome for this use case and I mention it only to show you that you can do it. You may find other uses for this in the future.

class MyModelForm (forms.ModelForm):
    gender = forms.ChoiceField (choices=..., initial='M', ...)
    class Meta:
        model=MyModel

-OR-

If you want a ModelForm that is bound to a particular instance of your model, you can pass an 'instance' of your model which causes Django to pull the selected value from that model.

form = MyModelForm (instance=someinst)



回答2:


Surely default will do the trick?

e.g.

gender = models.CharField(max_length=1, choices=GENDER_CHOICES, default='M', null=True)


来源:https://stackoverflow.com/questions/624265/how-do-i-make-a-django-modelform-menu-item-selected-by-default

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!