How to use login_required in django rest view

后端 未结 3 1781
不知归路
不知归路 2020-12-16 15:12

I am trying to use a custom login url in specific view

@login_required(login_url=\'/account/login/\')
class home(APIView):
    renderer_classes = (TemplateHT         


        
3条回答
  •  生来不讨喜
    2020-12-16 15:45

    Decorators can only be used on functions, not classes.

    However, for decorating class-based views the django docs suggest this:

    Decorating the class

    To decorate every instance of a class-based view, you need to decorate the class definition itself. To do this you apply the decorator to the dispatch() method of the class.

    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. The method_decorator decorator transforms a function decorator into a method decorator so that it can be used on an instance method. For example:

    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)
    

提交回复
热议问题