【问题标题】:Set initial value in ModelChoiceField at setup在设置时在 ModelChoiceField 中设置初始值
【发布时间】:2019-03-01 15:50:22
【问题描述】:

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

我认为这可以在 Forms.pySetBillingInfo 类中完成,但无法让它工作。假设我想默认为 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


    【解决方案1】:

    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
        )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-22
      • 1970-01-01
      • 2016-04-12
      • 1970-01-01
      • 2019-01-23
      • 2016-12-23
      • 2014-05-15
      • 2012-04-12
      相关资源
      最近更新 更多