Skip to content Skip to sidebar Skip to footer

Restricting User Access To Different Apps In Django

I have two models in my project. Both of which reference the User class (I used the User model to gain access to methods such as authenticate and login_required) class Customer(mod

Solution 1:

user_passes_test is just a simple decorator, and yes it does redirect to the login url as documented.

Now since user_passes_test calls your own test function, if you want to return a 403 Forbidden instead you just have to raise PermissionDenied instead of returning False:

from django.core.exceptions import PermissionDenied, ObjectDoesNotExist

def check_if_merchant(user):
    try:
        user.merchants
    except (AttributeError, ObjectDoesNotExist):
        raise PermissionDenied
    else:
        return True

Alternatively you can first check if you have a logged in user and return False if not, to redirect non logged in users to the login page:

from django.core.exceptions import PermissionDenied, ObjectDoesNotExist

def check_if_merchant(user):
    if user.is_anonymous():
        return False
    try:
        user.merchants
    except (AttributeError, ObjectDoesNotExist):
        raise PermissionDenied
    else:
        return True

Post a Comment for "Restricting User Access To Different Apps In Django"