Multiple decorators for a view in Django: Execution order

后端 未结 4 2038
温柔的废话
温柔的废话 2020-12-24 01:31

I am trying to decorate a Django view by two decorators, one for checking login, and one for checking is_active.

The first one is the built-in @login_required<

4条回答
  •  情书的邮戳
    2020-12-24 02:33

    Decorators are applied in the order they appear in the source. Thus, your second example:

    @login_required
    @active_required
    def foo(request):
        ...
    

    is equivalent to the following:

    def foo(request):
        ...
    foo = login_required(active_required(foo))
    

    Thus, if the code of one decorator depends on something set by (or ensured by) another, you have to put the dependent decorator "inside" the depdended-on decorator.

    However, as Chris Pratt notes, you should avoid having decorator dependencies; when necessary, create a single new decorator that calls both in the right order.

提交回复
热议问题