How can i put authentication on class views in django

You can do that in many ways like

https://docs.djangoproject.com/en/dev/topics/class-based-views/#decorating-class-based-views

  1. Either this
 urlpatterns = patterns('',
        (r'^about/', login_required(TemplateView.as_view(template_name="secret.html"))),
        (r'^vote/', permission_required('polls.can_vote')(VoteView.as_view())),
    )
  1. Or this
class ProtectedView(TemplateView):
    template_name = 'secret.html'

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

For Django 1.9 or greater; Class Based Views (CBVs) can utilize the mixin from the auth package. Simply import using the below statement -

from django.contrib.auth.mixins import LoginRequiredMixin

A mixin is a special kind of multiple inheritance. There are two main situations where mixins are used:

  1. You want to provide a lot of optional features for a class.
  2. You want to use one particular feature in a lot of different classes.

Learn more : What is a mixin, and why are they useful?


CBV using login_required decorator

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 example code uses django-vanilla to easily create Class Based Views (CBVs). The same can be achieved by using Django's inbuilt CBVs with some extra lines of code.

Tags:

Python

Django