Django: reuse login_required decorator inside other decorators

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

So, in the example, if active decorators have "active_required" for decorators, we will not need to use both active_required and login_required in the same view.

We should have a "login_required" decorator "somehow" inside "active_required".

Can this be done using the standard login_required decorator that comes with django?

My requirements: 1) if the user is not authenticated, I must redirect him to LOGIN_URL 2) if the user is authenticated (login_required) but not active, I must redirect him to the page to "reactivate" my account 3) if the user is authenticated and active, the user can access the view

Thanks in advance

+6
source share
1 answer

When you think about your question, it was easier for me to create a simple active_required decorator. It is very simple because we can use the user_passes_test function in django.contrib.auth.decorators .

Then the question arises: "How to combine login_required and active_required into one decorator?". We need to define a function that:

  • takes a view function as an argument
  • applies both decorators to it to create a new view function
  • returns a 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 
+8
source

Source: https://habr.com/ru/post/909769/


All Articles