假设我有以下模型:
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')
然后在 views.py 中,我为 Holder 创建了一个表单集,并将其传递给模板:
formset = modelformset_factory(Holder, fields =('other_field',))
data = {'formset': formset}
在模板.html中,我想访问相关对象的一个字段。我尝试过:
{% for form in formset %}
{{ form.object.related_field }}
{{ form.other_field }}
{% endfor %}
然后,显示other_field,但不显示related_field。如何在模板中以related_field显示值?
好的,我终于通过使用formset实例解决了它:
{% for form in formset %}
{{ form.instance.object.related_field }}
{{ form.other_field }}
{% endfor %}