João Areias
João Areias

Reputation: 1428

Django template with multiple models

I have a template from which I need to render information from multiple models. My models.py look something like this:

# models.py
from django.db import models

class foo(models.Model):
    ''' Foo content '''

class bar(models.Model):
    ''' Bar content '''

I also have a file views.py, from which I wrote according to this Django documentation and the answer given here, and looks something like this:

# views.py
from django.views.generic import ListView
from app.models import *

class MyView(ListView):
    context_object_name = 'name'
    template_name = 'page/path.html'
    queryset = foo.objects.all()

    def get_context_data(self, **kwargs):
        context = super(MyView, self).get_context_data(**kwargs)
        context['bar'] = bar.objects.all()

        return context

and my urlpatterns on urls.py have the following object:

url(r'^path$',views.MyView.as_view(), name = 'name'),

My question is, on the template page/path.html how can I reference the objects and the object properties from foo and bar to display them in my page?

Upvotes: 5

Views: 4887

Answers (2)

2ps
2ps

Reputation: 15916

To access foos from your template, you have to include it in the context:

# views.py
from django.views.generic import ListView
from app.models import *
class MyView(ListView):
    context_object_name = 'name'
    template_name = 'page/path.html'
    queryset = foo.objects.all()

    def get_context_data(self, **kwargs):
        context = super(MyView, self).get_context_data(**kwargs)
        context['bars'] = bar.objects.all()
        context['foos'] = self.queryset
        return context

Now in your template you can access the value by referencing the key that you used when creating the context dictionary in get_context_data:

<html>
<head>
    <title>My pathpage!</title>
</head>
<body>
    <h1>Foos!</h1>
    <ul>
{% for foo in foos %}
    <li>{{ foo.property1 }}</li>
{% endfor %}
    </ul>

    <h1>Bars!</h1>
    <ul>
{% for bar in bars %}
    <li>{{ bar.property1 }}</li>
{% endfor %}
    </ul>
</body>
</html>

Upvotes: 5

user2390182
user2390182

Reputation: 73450

For the most simple cases, just use the common django templating language constructions, forloop-tag and {{}} variable notation:

{% for b in bar %}   # should be called 'bars' in the context, really
  {{ b }}            # will render str(b)
  {{ b.id }}         # properties, fields
  {{ b.get_stuff }}  # callables without parentheses
{% endfor %}

See the template language docs for more.

Upvotes: -1

Related Questions