2

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

4

2 回答 2

4

您需要先应用一个method_decorator,然后将其传递给login_required函数装饰器。

类上的方法与独立函数并不完全相同,因此您不能只将函数装饰器应用于方法。您需要先将其转换为方法装饰器。

为了更清楚,Django 的视图装饰器返回一个带有签名的函数,(request, *args, **kwargs)但是对于基于类的视图,签名应该是(self, request, *args, **kwargs). 现在,method_decorator它的作用是将第一个签名转换为第二个签名。

来自关于装饰基于类的视图的文档:

装饰器将method_decorator函数装饰器转换为方法装饰器,以便可以在实例方法上使用它。

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)
于 2015-08-11T18:42:21.330 回答
0

当使用基于类的视图时,最好使用 LoginRequiredMixin 而不是 @login_required 装饰器。它执行基本相同的功能。

    class ProfileView(LoginRequiredMixin, TemplateView):
        template_name='profile.html'
于 2020-05-28T17:20:30.877 回答