Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest - Use @action with custom decorator

Tags:

rest

django

I have a Rest API in Django and I have the following method in a class that extends ModelViewSet:

@custom_decorator
@action(methods=['get'], detail=False, url_name="byname", url_path="byname")
def get_by_name(self, request):
    # get query params from get request
    username = request.query_params["username"]
    experiment = request.query_params["experiment"]

If I remove the first annotator everything works fine. But when I am trying to call this function with both decorators, it does not even find the specific url path.

Is it possible to use multiple decorators along with the @action decorator?

like image 325
sthemeli Avatar asked Dec 05 '19 12:12

sthemeli


1 Answers

I was having the same issue and fixed it the following way:

from functools import wraps

def custom_decorator(func):
  # ADD THIS LINE TO YOUR CUSTOM DECORATOR
  @wraps(func)
  def func_wrapper(*args, **kwargs):
    return func(*args, **kwargs)
  return func_wrapper

@action(methods=['get'], detail=False, url_name="byname", url_path="byname")
@custom_decorator
def get_by_name(self, request):
  # other code

I believe the issue is that the action decorator does not recognize the function after adding custom_decorator because the name is changed, so by adding @wraps(func) the function name stays the same. (@wraps docs)

like image 110
Adolfo Avatar answered Oct 26 '22 01:10

Adolfo