Python 如何在django rest视图中使用所需的登录名
我试图在特定视图中使用自定义登录urlPython 如何在django rest视图中使用所需的登录名,python,django,django-rest-framework,Python,Django,Django Rest Framework,我试图在特定视图中使用自定义登录url @login_required(login_url='/account/login/') class home(APIView): renderer_classes = (TemplateHTMLRenderer,) def get(self, request, format=None): template = get_template(template_name='myapp/template.html')
@login_required(login_url='/account/login/')
class home(APIView):
renderer_classes = (TemplateHTMLRenderer,)
def get(self, request, format=None):
template = get_template(template_name='myapp/template.html')
return Response({}, template_name=template.template.name)
但追踪显示
File "django/core/handlers/base.py", line 132, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "django/contrib/auth/decorators.py", line 22, in _wrapped_view
return view_func(request, *args, **kwargs)
TypeError: __init__() takes exactly 1 argument (2 given)
是否可以在基于类的视图中使用自定义登录\u
谢谢大家! 装饰符只能用于函数,不能用于类 但是,对于装饰基于类的视图,建议如下: 装饰班级 要修饰基于类的视图的每个实例,需要修饰 类定义本身。为此,您将装饰器应用于
dispatch()
类的方法
类上的方法与独立函数不同,因此
您不能只将函数装饰器应用于该方法–您需要
首先将其转换为方法装饰器。method\u decorator
decorator将函数decorator转换为方法decorator,因此
它可以用于实例方法。例如:
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView
class ProtectedView(TemplateView):
template_name = 'secret.html'
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(ProtectedView, self).dispatch(*args, **kwargs)
我认为您正在搜索django rest框架APIView; 在这里您可以使用权限类; 请参阅本文档 添加到seetings.py
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
}
from rest_framework.permissions import IsAuthenticated
class home(APIView):
renderer_classes = (TemplateHTMLRenderer,)
permission_classes = (IsAuthenticated,)
def get(self, request, format=None):
template = get_template(template_name='myapp/template.html')
return Response({}, template_name=template.template.name)
由于Django 1.9,您也可以使用Mixin来控制基于类的视图中的权限:
回答得好,投了赞成票。也许值得一提和解释的是,如果装饰需要在多个视图中应用,最好的选择是定义和使用一个MixinBut如何添加一个自定义的登录url,比如
login\u url='/account/login/'
?我猜@method\u装饰器(需要登录(login\u url='/account/login/'))
这可能是最干净的解决方案,因为普通的装饰程序在restframework端点上没有用处。链接现在已失效