Home > Blockchain >  What is right order for defining decorators in django views
What is right order for defining decorators in django views

Time:12-02

I want to set more than one decorator for my django function view. The problem is that I can't figure out how should be the order of decorators.

For example this is the view I have:

@permission_classes([IsAuthenticated])
@api_view(["POST"])
def logout(request):
    pass

In this case, first decorator never applies! neither when request is POST nor when it's GET!

When I change the order, to this:

@api_view(["POST"])
@permission_classes([IsAuthenticated])
def logout(request):
    pass

the last decorator applies before the first one, which is not the order that I want.

I want the decorator @api_view(["POST"]) to be applied first, and then @permission_classes([IsAuthenticated]).

How should I do that?

CodePudding user response:

This is the correct way of ordering 'api_view' consider the view as API view that the decorator is defined by restframework.

from rest_framework.decorators import api_view, permission_classes

@api_view(["POST"])
@permission_classes([IsAuthenticated])
def logout(request):
    pass
  • Related