user2496550 user2496550 - 1 month ago 6
Python Question

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.

Answer

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
Comments