How can I put authentication in class views in django

In 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 in a class based view

 @login_required classMyCreateView(CreateView): 

It gives an error

'function' object has no attribute 'as_view'

+4
source share
2 answers

You can do this in many ways, for example

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

  • Or is it
  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 that

class ProtectedView (TemplateView): template_name = 'secret.html'

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

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.

0
source

All Articles