Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refer to multiple Models in View/Template in Django

I'm making my first steps with Python/Django and wrote an example application with multiple Django apps in one Django project. Now I added another app called "dashboard" where I'd like to display data from different apps. At the moment I still use this simple class-based generic view, which shows the entries of my little contacts-App on the dashboard:

views.py:

from django.views.generic import ListView
from contacts.models import Contact

class ListDashboardView(ListView):
     model = Contact
     template_name = 'dashboard.html'

urls.py:

url(r'^$', dashboard.views.ListDashboardView.as_view(),
    name='dashboard-list',),

In dashboard.html I do:

<ul>
  {% for contact in object_list %}
    <li class="contact">{{ contact }}</li>
  {% endfor %}
</ul>

Can anybody explain to a beginner how to access multiple models in my template? I'd like to show not only the contacts from my 'contacts' app but also data from other apps such as my 'inventory' app and a third app.

I know, I have to import it:

from inventory.models import Asset
from polls.models import Poll

But what has to be done to pass all this data to my single template using a view? And how can I access that data in my template?

The solution may be in Django Pass Multiple Models to one Template but I must confess that I don't really understand it.

like image 223
user2496550 Avatar asked Aug 24 '13 13:08

user2496550


2 Answers

You need to override the get_context_data method and pass whatever you want to in context:

class ListDashboardView(ListView):
    model = Contact
    template_name = 'dashboard.html'

    def get_context_data(self, **kwargs):
        ctx = super(ListDashboardView, self).get_context_data(**kwargs)
        ctx['polls'] = Poll.objects.all()
        return ctx
like image 146
Aamir Rind Avatar answered Oct 20 '22 03:10

Aamir Rind


To add to Aamir's answer

in the html you would do:

{% for contact in object_list %}
<li>{{contact.object}}</li>
{% endfor %}

to reference the "contact" model objects

and

{% for x in polls %}
<li>{{ x.object }}</li>
{% endfor %}

to reference the "polls" model objects

(this wasn't intuitive to me at first).

like image 31
der0keks Avatar answered Oct 20 '22 02:10

der0keks