【问题标题】:How to render Form Choices manually如何手动呈现表单选择
【发布时间】:2017-04-23 12:05:09
【问题描述】:

我在 form.py

SELECT_PRODUCT = [
    ('item1', 'item1'),
    ('item2', 'item2'),
    ('item3', 'item3'),
    ('item4', 'item4'),
]

class OrderBonus(forms.Form):
    select_product = forms.CharField(widget=forms.Select(choices=SELECT_PRODUCT ))

在 html 中,我需要单独呈现每个选项:

<select name="{{ form_bonus.select_product .name }}">
    <option value="{{form_bonus.select_product.field.choice.0}}">{{form_bonus.select_product.field.choice.0}}</option>
    <option value="{{form_bonus.select_product.field.choice.1}}">{{form_bonus.select_product.field.choice.1}}</option>
    <option value="{{form_bonus.select_product.field.choice.2}}">{{form_bonus.select_product.field.choice.2}}</option>
 </select>

我尝试不同的方式: 1)form_bonus.select_product.field.choice.0 2)form_bonus.select_product.field.choice.[0] 3)form_bonus.select_product.field.choice.("0")

我尝试迭代:

{% for choice in form_bonus.select_product.field.choices %}
    {{ choice }}
{% endfor %}

{% for value, text in form_bonus.select_product.field.choices %}
    {{ value}} - {{ text }}
{% endfor %}

任何人都知道如何覆盖 Select Widget 以使用每个选项: form_bonus.select_product.field.choice.0 等等。

Python 3.5.2 和 Django 1.10

【问题讨论】:

    标签: django django-widget


    【解决方案1】:

    试试这个:

    <select name="{{ form_bonus.select_product.name }}">
        {% for choice in form_bonus.select_product.field.choices %}
            <option value="{{ choice.0 }}">{{ choice.1 }}</option>
        {% endfor %}
    </select>
    

    但请确保使用ChoiceField 而不是CharField

    class OrderBonus(forms.Form):
        select_product = forms.ChoiceField(choices=SELECT_PRODUCT)
    

    如果你愿意,你可以简单地写 {{ form_bonus.as_p }} 而不是循环。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-25
      • 1970-01-01
      相关资源
      最近更新 更多