Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django view - user passes test multiple conditions?

Tags:

django

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

like image 897
AlexW Avatar asked Aug 10 '18 15:08

AlexW


1 Answers

OR-logic

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

AND-logic

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
like image 157
Willem Van Onsem Avatar answered Oct 06 '22 22:10

Willem Van Onsem