【发布时间】:2019-03-01 15:50:22
【问题描述】:
我试图弄清楚如何在创建 ModelChoiceField 时设置它的初始值(而不是在创建表单时)。下面是我现在拥有的一个非常简化的示例,我想在渲染时为 State 和 Country 设置默认值。
我认为这可以在 Forms.py 的 SetBillingInfo 类中完成,但无法让它工作。假设我想默认为 California 为州和 United States 为国家。有办法设置吗?
FORMS.PY
class SetBillingInfo(forms.Form):
state = forms.ModelChoiceField(
queryset=States.objects.all().order_by('group_order','name'),
to_field_name='name',
label = '',
required=False
)
country = forms.ModelChoiceField(
queryset=Country.objects.all().order_by('group_order','name'),
to_field_name='name',
label = '',
required=True
)
VIEWS.PY
billinginfo = SetBillingInfo(initial=request.GET)
return render(request, 'index.html',{'billinginfo': billinginfo})
INDEX.HTML(这并不完全正确,但你明白了)
{% for field in billinginfo %}
<select class="FormRow">
{{ field }}
</select>
{% endfor %}
【问题讨论】:
标签: django django-forms django-views