Django loop over modelchoicefield querys模型

2024-10-02 02:27:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我的问题是:

我需要遍历模板中ModelChoiceField的查询集,这样我就可以创建一个单选按钮列表,其中包括模型的area字段和description字段。所以我的模型看起来像这样。。。在

在模型.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 }}

我所做的:

^{pr2}$

这给了我一个包含主键和区域的元组列表,但是如果我这样做,我就无法访问description字段。在

{% for item in form_from_view.an_example.field.queryset %}
    {{ item }}
{% endfor %}

这给了我一个实际的模型实例,我确实有权访问{{ item.description }},但不幸的是,这并没有在整个queryset上循环;它只给了我第一条记录,而不是像我预期的那样,在queryset中的每条记录。在

其他

在视图.py在

form_from_view = MyForm(instance=my_form_instance)

在表单.py在

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

AnExample.objects.all()应返回3条记录。我可以在管理员那里验证。在


Tags: instancepy模型form模板truemodels记录
1条回答
网友
1楼 · 发布于 2024-10-02 02:27:42

您不应该尝试在模板中循环字段选择。相反,您应该自定义表单字段本身以提供所需的输出。在

在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 }}来输出整个内容。在

相关问题 更多 >

    热门问题