Django Generic Views with Mixins


The true power of generic views unfolds when you combine them with Mixins. A mixin is a just another class defined by you whose methods can be inherited by your view class.

Assume you want every view to show the additional variable 'page_title' in the template. Instead of overriding the get_context_data method each time you define the view, you create a mixin with this method and let your views inherit from this mixin. Sounds more complicated than it actually is:

# Your Mixin
class CustomMixin(object):
    def get_context_data(self, **kwargs):
        # Call class's get_context_data method to retrieve context
        context = super().get_context_data(**kwargs) 
        context['page_title'] = 'My page title'
        return context

# Your view function now inherits from the Mixin
class CreateObject(CustomMixin, CreateView):
    model = SampleObject
    form_class = SampleObjectForm
    success_url = 'url_to_redirect_to'

# As all other view functions which need these methods
class EditObject(CustomMixin, EditView):
    model = SampleObject
    # ...

The beauty of this is that your code becomes much more structured than it is mostly the case with functional views. Your entire logic behind specific tasks sits in one place and one place only. Also, you will save tremendous amounts of time especially when you have many views that always perform the same tasks, except with different objects