Django: re-use login_required decorator inside other decorators

心不动则不痛 提交于 2019-12-12 08:53:20

问题


According to one of the comments in https://stackoverflow.com/a/8715790/210481, which I agree with, we should avoid multiple decorators if one depends on the other.

So, in the example, if we have a decorator "active_required" for active users, we should not have to use both active_required and login_required on the same view.

We should have "login_required" decorator "called" somehow inside the "active_required" one.

Is it possible to do it with the standard "login_required" decorator that comes with django?

My requirements are: 1) if the user is not authenticated, I should redirect him to LOGIN_URL 2) if the user is authenticated (passed login_required), but is not active, I should redirect him to a page to "re-activate" his account 3) if the user is authenticated and active, the user can access the view

Thanks in advance


回答1:


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


来源:https://stackoverflow.com/questions/9521966/django-re-use-login-required-decorator-inside-other-decorators

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