NickP
NickP

Reputation: 1414

Referencing model attributes within form

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 %}

Upvotes: 0

Views: 18

Answers (1)

dirkgroten
dirkgroten

Reputation: 20692

If you're using a ModelForm for all your forms, you need to initialise it with the model instance that's being updated (MyForm(data=request.POST, instance=...)).

You can access the instance of the form, it's just an attribute on the form: form.instance.

Note that it's always present on the ModelForm, even if you don't pass an instance when initialising. In that case it's an initialised, not saved, instance of the model of your form. So form.instance.pk = None in that case.

Upvotes: 1

Related Questions