2012-10-01 121 views
1

我有一个Django表单集与一组初始数据,加载一个外键关系对象到初始形式:Django的FORMSET访问初始数据模板

{{ 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作为div#id。我使用ModelCormSet作为CellCount,它传递一个CellType对象列表作为其初始数据。

回答

4

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

{{ form.initial.cell.machine_name }} 
+0

优秀 - 感谢您的! – jvc26

0

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

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

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

<div id="{{ form|machine_name }}">