问题描述
我有一个ModelForm包含一个ModelChoiceField,使用RadioSelect小部件。
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 form.visible_fields%}
{%if field.name ==one_property%}
< table>
{%for field.choices%}
< tr>
< td>< input value ={{choice.id}}type =radioname =one_property/>{{choice.description}}</td>
< td>< img src ={{choice.img_url}}/>< / td>
< / tr>
{%endfor%}
< / table>
{%endif%}
{%endfor%}
不幸的是。选择返回对象的id和标签的元组,而不是查询器中的实例。
有没有一种简单的方法来获取一个ModelChoiceField的选项的实例在一个模板中?
在深入研究ModelChoiceField的django源之后,我发现它有一个属性queryset。 >
我可以使用类似...
{%for field在form.visible_fields%}
{%if field.name ==one_property%}
< table>
{%for field.queryset%}
< tr>
< td>< input value ={{choice.id}}type =radioname =one_property/>{{choice.description}}</td>
< td>< img src ={{choice.img_url}}/>< / td>
< / tr>
{%endfor%}
< / table>
{%endif%}
{%endfor%}
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
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 %}
Unfortunately field.choices returns a tuple of the object's id and the label and not an instance from the queryset.
Is there a simple way to get instances of the choices for a ModelChoiceField to use within a template?
After delving into the django source for ModelChoiceField I discovered it has a property "queryset".
I was able to use something like...
{% 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实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!