View mixins
Mixins are the essence of DRY code in class-based views. Like model mixins, a view mixin takes advantage of Python's multiple inheritance to easily reuse chunks of functionality. They are often parent-less classes in Python 3 (or derived from object
in Python 2 since they are new-style classes).
Mixins intercept the processing of views at well-defined places. For example, most generic views use get_context_data
to set the context dictionary. A derived class or mixin can insert an additional context variable, such as feed
that contains a user's feed of posts. Here is how that mixin would look like:
class FeedMixin: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["feed"] = models.Post.objects.viewable_posts( self.request.user) return context
The get_context_data
method first populates the context by calling its namesake in all the base classes. Next, it updates the context dictionary with the feed...