jvc26
jvc26

Reputation: 6503

Django formset access initial data in template

I have a Django formset with a set of initial data which loads a foreignkey relation object into the initial form:

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

The relevant models look like this:

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)

I want to be able to display the machine_name of the cell referred to by the cell attribute of the CellCount model as the #id of the div. I use a ModelFormSet for the CellCount, which is passed a list of CellType objects as its initial data.

Upvotes: 1

Views: 2612

Answers (2)

Alasdair
Alasdair

Reputation: 308779

The form's initial data is stored in form.initial, so try:

{{ form.initial.cell.machine_name }}

Upvotes: 5

Ian Clelland
Ian Clelland

Reputation: 44112

I don't think that you can use the form fields to traverse models and get at the machine name, but I'll check. If you can, the syntax will be something like

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

But I think that you are going to need to write a custom template filter for this. It can just take the form as an argument, and return the machine name associated with it (or blank if the form is unbound). Then you will be able to write

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

Upvotes: 0

Related Questions