I am hoping to edit multiple models at the same time on a singe page. Rather than using formsets, I got this to work with an array of forms that I loop through in the template in the view:
{% extends 'app_base.html' %} {% block content %}
<p>{{message}}</p>
<form method="post">{% csrf_token %} {% for form in forms %}{{ form.as_p }}{% endfor %}
<input type="submit" value="Submit" />
</form>
{% endblock %}
However, annoying, I cannot see what I am editing in the output as its just a bunch of text boxes without labels.
As such, is there any way to access the model attributes alongside the form as I loop through like:
{% for form in forms %}{{form.object.name}}: {{ form.as_p }}{% endfor %}
答案 0 :(得分:1)
如果所有表单都使用ModelForm
,则需要使用正在更新的模型实例(MyForm(data=request.POST, instance=...)
)对其进行初始化。
您可以访问表单的instance
,它只是表单上的一个属性:form.instance
。
请注意,即使您在初始化时未通过ModelForm
,它也始终存在于instance
上。在这种情况下,它是表单模型的初始化而不是保存的实例。因此,在这种情况下,form.instance.pk = None
。