1

我有一个带有一组初始数据的 Django 表单集,它将外键关系对象加载到初始表单中:

{{ cellcountformset.management_form }}
{% for form in cellcountformset %}
<div id="">
    {{ form.errors }}
    {{ form.as_p }}
</div>
{% endfor %}

相关模型如下所示:

class CellType(models.Model):
    readable_name = models.CharField(max_length=50)
    machine_name = models.CharField(max_length=50)
    comment = models.TextField(blank=True)

class CellCount(models.Model):
    cell_count_instance = models.ForeignKey(CellCountInstance)
    cell = models.ForeignKey(CellType)
    normal_count = models.IntegerField()
    abnormal_count = models.IntegerField()
    comment = models.TextField(blank=True)

我希望能够将 CellCount 模型的单元格属性所引用的单元格的 machine_name 显示#iddiv. 我为 CellCount 使用了 ModelFormSet,它传递了一个 CellType 对象列表作为其初始数据。

4

2 回答 2

5

表单的初始数据存储在 中form.initial,因此请尝试:

{{ form.initial.cell.machine_name }}
于 2012-10-01T22:09:55.733 回答
0

我不认为您可以使用表单字段来遍历模型并获取机器名称,但我会检查一下。如果可以,语法将类似于

<div id="{{ form.fields.cell.machine_name }}">

但我认为您将需要为此编写一个自定义模板过滤器。它可以只将表单作为参数,并返回与其关联的机器名称(如果表单未绑定,则返回空白)。然后你就可以写了

<div id="{{ form|machine_name }}">
于 2012-10-01T20:41:36.680 回答