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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…