【问题标题】:Django loop over modelchoicefield querysetDjango 循环遍历 modelchoicefield 查询集
【发布时间】: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 已更新。

标签: python django


【解决方案1】:

您不应该尝试遍历模板中的字段选择。相反,您应该自定义表单字段本身以提供您想要的输出。

在 ModelChoiceField 的情况下,正如文档所解释的那样,自定义输出的方法是对该字段进行子类化并定义 label_from_instance

class AnExampleModelChoiceField(ModelChoiceField):
    def label_from_instance(self, obj):
        return '{}: {}'.format(obj.area, obj.description)

class myForm(forms.ModelForm):
    an_example = forms.AnExampleModelChoiceField(widget=forms.RadioSelect,
        queryset=AnExample.objects.all(),
        required=True)

现在您可以在模板中执行{{ form_from_view.an_example }} 来输出整个内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-15
    • 2013-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-22
    • 1970-01-01
    • 2023-03-22
    相关资源
    最近更新 更多