简体   繁体   中英

How can i put authentication on class views in 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'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM