This repository has been archived by the owner on Sep 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 42
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.
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)
Did the mixin code look familiar? We can now remove the dispatch methods from our two views, and inherit from the mixin.
- Delete the dispatch method from both views.
- 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):
...