小编典典

如何在模板中获取ModelChoiceField实例

django

我有一个使用RadioSelect小部件包含ModelChoiceField的ModelForm。

class MyAForm(forms.ModelForm):
    one_property = models.ModelChoiceField(
        widget=forms.RadioSelect,
        queryset=MyBModel.objects.filter(visible=True),
        empty_label=None)
    class Meta:
        model = MyAModel

我要在单选按钮旁边显示MyBModel上的属性。我会label_from_instance在ModelChoiceField的子类上进行重写,但这不允许我做我想做的事情,因为我希望单选按钮出现在每个选择项都有一行的表中。

所以我在模板中的某处想要…

{% for field in form.visible_fields %}
    {% if field.name == "one_property" %}
    <table>
        {% for choice in field.choices %}
            <tr>
                <td><input value="{{choice.id}}" type="radio" name="one_property" />{{choice.description}}</td>
                <td><img src="{{choice.img_url}}" /></td>
            </tr>
        {% endfor %}
    </table>
    {% endif %}
{% endfor %}

不幸的是,field.choices返回对象的ID和标签的元组,而不是queryset中的实例。

是否有一种简单的方法来获取ModelChoiceField的选择实例以在模板中使用?


阅读 904

收藏
2020-04-03

共1个答案

小编典典

深入研究ModelChoiceField的django源代码后,我发现它具有属性“ queryset”。

我能够使用类似…

{% for field in form.visible_fields %}
    {% if field.name == "one_property" %}
    <table>
        {% for choice in field.queryset %}
            <tr>
                <td><input value="{{choice.id}}" type="radio" name="one_property" />{{choice.description}}</td>
                <td><img src="{{choice.img_url}}" /></td>
            </tr>
        {% endfor %}
    </table>
    {% endif %}
{% endfor %}
2020-04-03