Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i put authentication on class views in django

Tags:

python

django

IN the Django docs they say this https://docs.djangoproject.com/en/dev/topics/auth/default/#user-objects

from django.contrib.auth.decorators import login_required

@login_required(login_url='/accounts/login/')
def my_view(request):

But how can i use login_required on class based view

@login_required
classMyCreateView(CreateView):

This gives error

'function' object has no attribute 'as_view'

like image 509
user175386049 Avatar asked Jan 14 '13 07:01

user175386049


People also ask

How do I authenticate in Django?

from django.contrib.auth import authenticate, login def my_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # Redirect to a success page. ... else: # Return an 'invalid ...

How does Django implement custom authentication?

To implement a custom authentication scheme, subclass BaseAuthentication and override the .authenticate(self, request) method. The method should return a two-tuple of (user, auth) if authentication succeeds, or None otherwise.

How do class based views work in Django?

A view is a callable which takes a request and returns a response. This can be more than just a function, and Django provides an example of some classes which can be used as views. These allow you to structure your views and reuse code by harnessing inheritance and mixins.


2 Answers

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)
like image 74
Mirage Avatar answered Oct 23 '22 06:10

Mirage


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.

like image 25
Suraj Avatar answered Oct 23 '22 05:10

Suraj