Search code examples
pythondjangodjango-templatesgeneric-foreign-key

Accessing a field through a GenericForeignKey in a django template formset


Suppose I have the following model:

class Holder(models.Model):
    other_field = models.BooleanField(default=True)
    object_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    object = GenericForeignKey('object_type', 'object_id')

Then in views.py, I have created a formset for Holder, and passed it to the template:

formset = modelformset_factory(Holder, fields =('other_field',))
data = {'formset': formset}

In template.html, I want to access one field of the related object. I have tried with:

{% for form in formset %}
     {{ form.object.related_field }}
     {{ form.other_field }}
{% endfor %}

Then, other_field is displayed but related_field is not. How could I display the value in related_field in the template?


Solution

  • Ok, I finally solved it by using the formset instance:

    {% for form in formset %}
        {{ form.instance.object.related_field }}
        {{ form.other_field }}
    {% endfor %}