gpt4 book ai didi

python - 如何在模板中获取 ModelChoiceField 实例

转载 作者:太空狗 更新时间:2023-10-29 17:17:04 26 4
gpt4 key购买 nike

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

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 但这不允许我做我想做的事,因为我希望单选按钮出现在一个表中,每个选择项都有一行。

所以在我的模板中的某处我想要类似...

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

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

最佳答案

在深入研究 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 %}

关于python - 如何在模板中获取 ModelChoiceField 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10300685/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com