如何在模板中获取 ModelChoiceField 实例 [英] How to get ModelChoiceField instances in the template

查看:25
本文介绍了如何在模板中获取 ModelChoiceField 实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a ModelForm that contains a ModelChoiceField using the RadioSelect widget.

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 上的一些属性.我会在 ModelChoiceField 的子类上覆盖 label_from_instance ,但这不允许我做我想做的事情,因为我希望单选按钮出现在一个表中,每个选择项都有一行.

There are attributes on MyBModel that I want to display next to the radio button. I would override label_from_instance on a sub-class of ModelChoiceField but this does not allow me to do what I want as I want the radio button to appear inside a table which has a row for each selection item.

所以在我的模板中的某个地方,我想要一些类似...

So somewhere in my template I want something like...

{% 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 和标签的元组,而不是查询集中的实例.

Unfortunately field.choices returns a tuple of the object's id and the label and not an instance from the queryset.

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

Is there a simple way to get instances of the choices for a ModelChoiceField to use within a template?

推荐答案

在深入研究 ModelChoiceField 的 django 源代码后,我发现它有一个属性queryset".

After delving into the django source for ModelChoiceField I discovered it has a property "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 %}

这篇关于如何在模板中获取 ModelChoiceField 实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆