Python django中@login\u required和@method\u decorator(login\u required)之间有什么区别
我是django的新手,我不知道django中的Python django中@login\u required和@method\u decorator(login\u required)之间有什么区别,python,django,Python,Django,我是django的新手,我不知道django中的@login\u required和@method\u decorator(login\u required)之间有什么区别,我们应该使用哪一种。提前感谢。方法修饰符将函数修饰符转换为方法修饰符,以便在实例方法上使用 login_decorator是一个函数decorator,因此它只能在视图函数中使用 来源:在基于函数的视图中使用@login\u required: @login_required def my_view(request)
@login\u required
和@method\u decorator(login\u required)
之间有什么区别,我们应该使用哪一种。提前感谢。方法修饰符将函数修饰符转换为方法修饰符,以便在实例方法上使用
login_decorator是一个函数decorator,因此它只能在视图函数中使用
来源:在基于函数的视图中使用
@login\u required
:
@login_required
def my_view(request):
return HttpResponse('hello')
您可以对基于类的视图使用@method\u decorator(需要登录)
@method_decorator(login_required, name='dispatch')
class MyView(TemplateView):
template_name = 'hello.html'
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(MyView, self).dispatch(*args, **kwargs)
但是,使用LoginRequiredMixin
可能更简单:
from django.contrib.auth.mixins import LoginRequiredMixin
class MyView(LoginRequiredMixin, TemplateView):
template_name = 'hello.html'