[Answered ]-Django Rest Framework – adding permissions for views based on groups?

0πŸ‘

βœ…

The IsCustomer class was not set up properly. This is what the class should look like:

class IsCustomer(permissions.BasePermission):

    def has_permission(self, request, view):
        if 'auth.is_customer' in request.user.get_all_permissions():
            return True
        return False

    def has_object_permission(self, request, view, obj):
        if 'auth.is_customer' in request.user.get_all_permissions():
            return True
        return False

From there, using the @permission_classes([IsCustomer]) works as intended. Therefore the final form of the view is:

@api_view(["POST"])
@permission_classes([IsCustomer])
def testing_post(request):
    try:
        someData = someCalculations()
        return Response(data=someData, status=status.HTTP_200_OK)
    except ValueError as e:
        return Response(e.args[0], status.HTTP_400_BAD_REQUEST)
πŸ‘€WhoDatBoy

1πŸ‘

The last block should work if you reference the class directly:

from rest_framework.decorators permission_classes, api_view

@api_view(["POST"])
@permission_classes([IsCustomer])
def my_func(request):
    # calculations
    return Response(...)

You can view the documentation with a similar example here:
https://www.django-rest-framework.org/api-guide/permissions/

πŸ‘€dthomh

Leave a comment