user2496550 user2496550 - 1 year ago 68
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:

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

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

url(r'^$', dashboard.views.ListDashboardView.as_view(),

In dashboard.html I do:

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

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 Source

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