Skip to content
This repository has been archived by the owner on Sep 17, 2023. It is now read-only.

09 Intro to Mixins

scotwk edited this page May 15, 2015 · 5 revisions

Remember how one of the advantages of CBVs is the ability to easily share code via inheritance? We need to add the login required decorator to each view we create if we want to require authentication, so this is a good spot to share code.

@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
    return super(NoteList, self).dispatch(request, *args, **kwargs)

Mixins are a place to put shared code to be used within views. They are not meant to be standalone objects, but rather to provide common functionality to views.

Create a mixin

Make a new file, note/mixins.py:

from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator


class LoginRequiredMixin(object):
    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)

Update views

Did the mixin code look familiar? We can now remove the dispatch methods from our two views, and inherit from the mixin.

  1. Delete the dispatch method from both views.
  2. Add the LoginRequiredMixin in to the inheritance. Important! LoginRequiredMixin must come first in the inheritance list

Example class definitions:

class NoteList(LoginRequiredMixin, ListView):
    ...

class NoteDetail(LoginRequiredMixin, DetailView):
    ...