Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django template with multiple models

Tags:

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?

like image 769
João Areias Avatar asked Jan 16 '17 18:01

João Areias


People also ask

What does {% mean in Django?

{% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

Does Django have template?

A Django template is a text document or a Python string marked-up using the Django template language. Some constructs are recognized and interpreted by the template engine. The main ones are variables and tags. A template is rendered with a context.

What is model form 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.


1 Answers

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>
like image 154
2ps Avatar answered Sep 21 '22 11:09

2ps