Function decorators with parameters on a class based view in Django

后端 未结 1 591
旧时难觅i
旧时难觅i 2021-02-12 18:31

The official documentation explains how to decorate a class based view, however I could not find any information on how to provide parameters to the decorator.<

1条回答
  •  深忆病人
    2021-02-12 19:12

    @method_decorator takes a function as parameter. If you want to pass a decorator with parameters, you only need to:

    • Evaluate the parameters in the decorator-creator function.
    • Pass the evaluated value to @method_decorator.

    In explicit Python code this would be:

    decorator = mydecorator(arg1, arg2, arg...)
    method_dec = method_decorator(decorator)
    
    class MyClass(View):
        @method_dec
        def my_view(request):
            ...
    

    So, using the syntactic sugar completely:

    class MyClass(View):
        @method_decorator(mydecorator(arg1, arg2, arg...))
        def my_view(request):
            ...
    

    0 讨论(0)
提交回复
热议问题