Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i access the model instance used by a form from a template?

Tags:

django

I am iterating over a formset made of modelforms in my template. I want to provide aditional information on that model. If the answer to this How to Access model from Form template in Django question would work, i could do this:

{% for form in formset.forms %}
Status:{{ form._meta.model.status }}
    {{form}}
{% endfor %}  

But that just throws the TemplateSyntaxError: Variables and attributes may not begin with underscores.

like image 914
marue Avatar asked Feb 15 '11 10:02

marue


People also ask

What is form AS_P in Django?

{{ form.as_p }} – Render Django Forms as paragraph. {{ form.as_ul }} – Render Django Forms as list.

What is forms ModelForm in Django?

Django Model Form It is a class which is used to create an HTML form by using the Model. It is an efficient way to create a form without writing HTML code. Django automatically does it for us to reduce the application development time.

How do you exclude a specific field from a ModelForm?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.

What is model form?

What are Model Forms? Model Forms are forms that are connected directly to models, allowing them to populate the form with data. It allows you to create a form from a pre-existing model. You add an inline class called Meta, which provides information connecting the model to the form.


2 Answers

I don't think that's what you want to do. A model is a class: it won't have a status, as that's a field which only gets a value for a particular instance.

I suspect what you mean to do is access the model instance associated with the form, which is just form.instance.

like image 128
Daniel Roseman Avatar answered Oct 30 '22 10:10

Daniel Roseman


If you create a property on the form that reads the value then you can access it very easily in the template.

class SomeForm(...):
  @property
  def status(self):
    return self._meta.model.status

...

       {{ form.status }}
like image 34
Ignacio Vazquez-Abrams Avatar answered Oct 30 '22 09:10

Ignacio Vazquez-Abrams