For Django 1.9 or higher; Classroom Views (CBVs) can use mixin from the auth package. Just import using the statement below -
from django.contrib.auth.mixins import LoginRequiredMixin
Mixin is a special kind of multiple inheritance. There are two main situations in which mixins are used:
- You want to provide many additional features for the class.
- You want to use one specific function in many different classes.
Read more: What is mixin and why are they useful?
CBV using login_required constructor
urls.py
from django.conf.urls import url from django.contrib.auth.decorators import login_required from .views import ListSecretCodes urlpatterns = [ url(r'^secret/$', login_required(ListSecretCodes.as_view()), name='secret'), ]
views.py
from vanilla import ListView class ListSecretCodes(LoginRequiredMixin, ListView): model = SecretCode
CBV using LoginRequiredMixin
urls.py
from django.conf.urls import url from .views import ListSecretCodes urlpatterns = [ url(r'^secret/$', ListSecretCodes.as_view(), name='secret'), ]
views.py
from django.contrib.auth.mixins import LoginRequiredMixin from vanilla import ListView class ListSecretCodes(LoginRequiredMixin, ListView): model = SecretCode
Note
The above code example uses django-vanilla to easily create class-based views (CBVs). The same can be done using the built-in CBV with Django with some additional lines of code.
source share