Question

First of all I'm a beginner in Django world so maybe what I'm trying to do is crazy or it's a misunderstanding of concepts, so here we go:

How we can see, generic view save us a lot of time for that common patterns we use all the time in our templates, one of these is the ListView that retrieve a list of our model according to a set of attributes

 from models import Post
 from django.views.generic import ListView, DetailView 


    class PostListView(ListView):
        model = Post
        template_name = 'blog/post_list.html'

We bind our Post model for make a ListView an set post_list.html as our template but... what happen when in our template we need to show more than one model? Imagining with this show a list of posts but we want to show another list of something in this template, for this purpose we can do that with generic views? or we have to do as old usual?

Was it helpful?

Solution

You can add additional information such as another list of unrelated models to the context passed to the template. The Django documentation shows the example below:

from django.views.generic import DetailView
from books.models import Publisher, Book

class PublisherDetail(DetailView):

    model = Publisher

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super(PublisherDetail, self).get_context_data(**kwargs)
        # Add in a QuerySet of all the books
        context['book_list'] = Book.objects.all()
        return context
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top