I am using class based views in Django. @login_required decorator is not redirecting to login page. It still shows the profile page.
class ProfileView(TemplateView):
template_name='profile.html'
@login_required(login_url='/accounts/login/')
def dispatch(self, *args, **kwargs):
return super(ProfileView, self).dispatch(*args, **kwargs)
Can anyone help me. I m new to Django and any help would be appreciated.
Thanks in advance
You need to apply a method_decorator
first and then pass it the login_required
function decorator.
A method on a class isn't quite the same as a standalone function, so you can't just apply a function decorator to the method. You need to transform it into a method decorator first.
To make it more clear, Django's view decorators return a function with a signature (request, *args, **kwargs)
but for class based-views, the signature should be of the form (self, request, *args, **kwargs)
. Now, what the method_decorator
does is that it transforms the first signature to the second.
From docs on decorating Class-based Views:
The
method_decorator
decorator transforms a function decorator into a method decorator so that it can be used on an instance method.
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
class ProfileView(TemplateView):
template_name='profile.html'
@method_decorator(login_required(login_url='/accounts/login/'))
def dispatch(self, *args, **kwargs):
return super(ProfileView, self).dispatch(*args, **kwargs)
When using class-based views, it's preferred to use the LoginRequiredMixin rather than the @login_required decorator. It performs essentially the same function.
class ProfileView(LoginRequiredMixin, TemplateView):
template_name='profile.html'
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.