Conditionally Apply Login_required Decorator In Django
I have a set of function in views.py which are currently only user-accessible. I'm asked to make it publicly accessible and currently I am using the @login_required decorator in my
Solution 1:
You can use user_passes_test
for this kind of behaviour.
from django.contrib.auth.decorators import user_passes_test
def public_check(user):
if user.is_public:
return True
@user_passes_test(public_check)
Solution 2:
It will not work with a decorator because decorators are evaluated and applied on import time and, as you've said, you need to get the object first, which is based on the request.
Since you've asked for an elegant solution, and I'm assuming you want to create a decorator for it so you can reuse it on multiple views, then the solution is a class-based view. You can implement the behavior that you want as a class-based view mixin, which you can mix-in to different class-based views. This improved flexibility is one of the reasons class-based views were introduced.
Post a Comment for "Conditionally Apply Login_required Decorator In Django"