Im using the below to make sure a user has a custom permission before allowing them to run the view. however I would like to add multiple conditions, i.e. a user has_perm sites.can_view_mgmt or sites.can_view_finanical
@user_passes_test(lambda u: u.has_perm('sites.can_view_mgmt'))
is it possible to have an or in user passes test?
Thanks
If at least one of the conditions has to be satisfied, you can use an or
in the lambda expression:
@user_passes_test(lambda u: u.has_perm('sites.can_view_mgmt') or u.has_perm('sites.can_view_mgmt'))
def some_view(request):
# ...
pass
If the list is large, you can use the any(..)
function:
need_one_of = ['sites.can_view_mgmt', 'sites.can_view_mgmt']
@user_passes_test(lambda u: any(map(u.has_perm, need_one_of)))
def some_view(request):
# ...
pass
If all conditions have to be satisfied, you can use an and
instead of an or
. Django however has a User.has_perms
function as well that checks if all permissions hold, so:
@user_passes_test(lambda u: u.has_perms(['sites.can_view_mgmt', 'sites.can_view_mgmt']))
def some_view(request):
# ...
pass
Or we can use the all(..)
function:
need_all_of = ['sites.can_view_mgmt', 'sites.can_view_mgmt']
@user_passes_test(lambda u: all(map(u.has_perm, need_all_of)))
def some_view(request):
# ...
pass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With