【发布时间】:2017-02-13 19:22:38
【问题描述】:
我的问题:
我需要在模板中遍历ModelChoiceField 的查询集,以便创建一个单选按钮列表,其中包括模型的区域字段和描述字段。所以我的模型看起来像这样......
models.py
class AnExample(models.Model):
id = models.AutoField(primary_key=True)
area = models.CharField(max_length=50)
description = models.TextField(blank=True, null=True)
def __unicode__(self):
return self.area
...我想在我的模板中创建单选按钮输入,以便表单看起来像这样:
<input type="radio">{{ model_instance.area }}: {{ model_instance.description }}
我尝试过的:
{% for choice in form_from_view.an_example.field.choices %}
{{ choice }}
{% endfor %}
这给了我一个带有主键和区域的元组列表,但是如果我这样做,我无权访问描述字段。
{% for item in form_from_view.an_example.field.queryset %}
{{ item }}
{% endfor %}
这给了我实际的模型实例,我确实可以访问{{ item.description }},但不幸的是这不会循环整个查询集; 它只给了我第一条记录,而不是我期望的查询集中的每条记录。
其他
views.py
form_from_view = MyForm(instance=my_form_instance)
forms.py
class myForm(forms.ModelForm):
an_example = forms.ModelChoiceField(widget=forms.RadioSelect,
queryset=AnExample.objects.all(),
required=True)
AnExample.objects.all() 应该返回 3 条记录。我可以在管理员中验证。
【问题讨论】:
-
这里的
form_from_view是什么? -
@DanielRoseman 我在
views.py中定义的表单变量,然后将其发送到带有render_to_response中的locals()的模板 -
是的,但它是什么? 显示代码.
-
@DanielRoseman 已更新。