在设置时在ModelChoiceField中设置初始值

时间:2018-09-25 23:48:57

标签: django django-forms django-views

我试图弄清楚如何在创建ModelChoiceField时设置初始值(而不是在表单创建时)。以下是我现在拥有的非常简化的示例,我想在渲染时为国家/地区设置默认值。

我认为可以在SetBillingInfo的{​​{1}}类中完成此操作,但无法使其正常工作。假设我要为州默认为加利福尼亚,为国家/地区默认为美国。有办法设置吗?

FORMS.PY

Forms.py

VIEWS.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
    )

INDEX.HTML(这不是完全正确,但您可以理解)

billinginfo = SetBillingInfo(initial=request.GET)
return render(request, 'index.html',{'billinginfo': billinginfo})

1 个答案:

答案 0 :(得分:0)

forms.py

default_state=States.objects.get(name='California')

state = forms.ModelChoiceField(
        queryset=States.objects.all().order_by('group_order','name'),
        to_field_name='name',
        label = '',
        initial=default_state,
        required=False
    )
相关问题