Django formset访问模板中的初始数据

时间:2012-10-01 19:37:21

标签: django django-templates django-forms

我有一个带有一组初始数据的Django formset,它将一个foreignkey关系对象加载到初始形式中:

{{ 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模型的cell属性引用的cell的machine_name显示为#id的{​​{1}}。我为CellCount使用ModelFormSet,它将CellType对象列表作为初始数据传递。

2 个答案:

答案 0 :(得分:5)

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

{{ form.initial.cell.machine_name }}

答案 1 :(得分:0)

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

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

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

<div id="{{ form|machine_name }}">
相关问题