Django: re-use login_required decorator inside other decorators

萝らか妹 提交于 2019-12-04 06:18:49

When thinking about your question, I found it easier to create a simple active_required decorator first. This is very easy, because we can use the the user_passes_test function in django.contrib.auth.decorators.

The question then changes to "how do I combine the login_required and active_required into one decorator?". We need to define a function which:

  1. takes a view function as it's argument
  2. applies both decorators to it to create a new view function
  3. returns the new view function

Putting it all together, you have the following:

from django.contrib.auth.decorators import user_passes_test, login_required

active_required = user_passes_test(lambda u: u.is_active, login_url=REACTIVATE_URL)

def active_and_login_required(view_func):
    decorated_view_func = login_required(active_required(view_func))
    return decorated_view_func
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!