[Django]-Django โ€“ decorators restrict "staff"

5๐Ÿ‘

โœ…

Your allowed_roles are strings, so group in allowed_roles will always be false. Especially since group is a QuerySet of Groups, so a collection. That collection can contain zero, one, or more groups.

You can check if the group exists with request.user.groups.filter(name__in=allowed_roles).exists(), so the decorator looks like:

from functools import wraps

def allowed_user(allowed_roles=()):
    def decorator(view_func):
        @wraps(view_func)
        def wrapper_func(request, *args, **kwargs):
            if request.user.groups.filter(name__in=allowed_roles).exists():
                return view_func(request, *args, **kwargs)
            else:
                return HttpResponse('You are not Authorized!')
        return wrapper_func
    return decorator

Leave a comment