Search code examples
pythondjangogenericsviewdjango-context

extra_context function for simple generic view in django


I have my page where I have my posts list, and I also want to have sidebar with suggestions. I used generic ListView for my posts, and needed to pass suggestions somehow so I used extra_context which should(?) work like that according to few examples I've read, but in template there is no 'suggestions' object.

class PostList(generic.ListView):
    model = models.Post
    paginate_by = 10
    context_object_name = 'mj'
    def get_queryset(self):
        return models.Post.objects.filter(user = self.request.user)
    def extra_context(self):
        return {'suggestions':models.Pla.objects}

I don't have experience in django so maybe there is better way to pass suggestions for sidebar. Maybe it's possible to do this with wrapping view function since I want to have suggestions..


Solution

  • Class-based views don't use extra_context the way the older function-based generic views did. Instead, the usual way to do this is with a custom get_context_data call as shown in the docs:

    https://docs.djangoproject.com/en/dev/topics/class-based-views/generic-display/#adding-extra-context

    The example in the docs is almost exactly what you're trying to do. You may want to follow its example further and pass in a queryset (models.Pla.objects.all()) rather than the manager object (models.Pla.objects).