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 in Chapter 3Models, to filter the posts.

A more general solution is to use StaticContextMixin from django-braces for static-context variables. For example, we can add an additional context variable, latest_profile, which contains the latest user to join the site:

class CtxView(StaticContextMixin, generic.TemplateView): 
    template_name = "ctx.html" 
    static_context = {"latest_profile": Profile.objects.latest('pk')} 

Here, static_context means anything that is unchanged from one to another to request. In that sense, you can mention QuerySets as well. However, our feed context variable needs self.request.user to retrieve the user's viewable posts. Hence, it cannot be included as a static context here.

Conversely, if the shared context is a static value and the generic view is derived from ContextMixin (most are), then they can be mentioned while calling as_view. For instance:

    path('myfeed/', views.MyFeed.as_view( 
        extra_context={'title': 'My Feed'})), 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.167.176