Solution details

Most generic class-based views are derived from ContextMixin. It provides the get_context_data method, which most classes override, to add their own context variables. While overriding this method, as a best practice, you will need to call get_context_data of the superclass first and then add or override your context variables.

We can abstract this in the form of a mixin, as we saw previously:

class FeedMixin(object): 
 
    def get_context_data(self, **kwargs): 
        context = super().get_context_data(**kwargs) 
        context["feed"] = models.Post.objects.viewable_posts(            self.request.user) 
        return context 

We can add this mixin to our views and use the added context variables in our templates. Notice that we are using the model manager defined ...

Get Django Design Patterns and Best Practices - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.