Book Image

Django Design Patterns and Best Practices

By : Arun Ravindran
Book Image

Django Design Patterns and Best Practices

By: Arun Ravindran

Overview of this book

Table of Contents (19 chapters)
Django Design Patterns and Best Practices
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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. It is a good place to insert an additional context, such as a feed variable that points to all posts a user can view, as shown in the following command:

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

The get_context_data method first populates the context by calling its namesake in all the bases classes. Next, it updates the context dictionary with the feed variable.

Now...