默认情况下,如何设置Django ModelForm菜单项? [英] How do I make a Django ModelForm menu item selected by default?
问题描述
GENDER_CHOICES =(
('M','男'),
('F','女'),
)
gender = models.CharField(max_length = 1,choices = GENDER_CHOICES,null =我正在使用一个ModelForm来生成一个新用户HTML表单。我的Google-fu似乎失败了我 - 如何使这个HTML表单默认在下拉框中选择男项? (即这样 selected =selected
)解决方案如果您需要选择默认值的空白表单,请使用您的字段的名称作为密钥,将初始字典传递给模型表单的构造函数:
form = MyModelForm(initial = {'gender':'M'})
-OR -
您可以使用Forms API的声明性来覆盖ModelForm的某些属性。但是,对于这种用例来说,这可能有点麻烦,我只提到你可以做到这一点。您可能会在将来找到其他用途。
class MyModelForm(forms.ModelForm):
gender = forms .ChoiceField(choices = ...,initial ='M',...)
class Meta:
model = MyModel
-OR -
如果你想要一个绑定到模型的特定实例的ModelForm,你可以传递您的模型的实例,导致Django从该模型中拉取所选值。
form = MyModelForm(instance = someinst)
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.)
解决方案 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)
这篇关于默认情况下,如何设置Django ModelForm菜单项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!