[Django]-Django Permission Required

3👍

The mechanism of Django Views and Django Rest Framework Views are a bit different, that’s why you’ve got that error message. permission_required will try to access user field of your view to check user permission using has_perm method. But APIView didn’t have user field inside of it.

To get rid of this, you might want to use permissions which provided by Django Rest Framework to restrict the access.

But if you still want to use built-in permission of Django to restrict the access to your view, you could create a Permission class which will use has_perm to check user permission. Like so:

from rest_framework import permissions
from rest_framework import exceptions

class ViewCompanyPermission(permissions.BasePermission):
    def has_permission(self, request, view):
        if not request.user.has_perm('api.view_company'):
            raise exceptions.PermissionDenied("Don't have permission")
        return True

and use it on your view via permission_classes field:

class CompanyDetailView(APIView):
    permission_classes = (ViewCompanyPermission, )
    def get(self, request, id):
        try:
            request_data = {}
            request_data['request_method'] = request.method
            request_data['id'] = id
            companies = Company.objects.get(id=id)
            status = rest_framework.status.HTTP_200_OK
            return Response(companies, status)

In case you want to replicas the permission_required behavior, you could do something like this:

from rest_framework import permissions
from rest_framework import exceptions

def permission_required(permission_name, raise_exception=False):
    class PermissionRequired(permissions.BasePermission):
        def has_permission(self, request, view):
            if not request.user.has_perm(permission_name):
                if raise_exception:
                    raise exceptions.PermissionDenied("Don't have permission")
                return False
            return True
    return PermissionRequired

Then you can use it like:

class CompanyDetailView(APIView):
    permission_classes = (permission_required("api.view_company", raise_exception=True), )
    # ...

3👍

You can’t easily use django permissions with django rest framework.

there is a tutorial about django-rest-framework permissions at:

https://www.django-rest-framework.org/api-guide/permissions/

1👍

Based on the description permission_required this decorator should be used for a function view, where first argument is request and you try to apply it for the class method where the first argument is self in your case instanse of the CompanyDetailView so you get the error. And you should use another way to check the permissions.

You can read some examples in here: decorators-on-django-class-based-views

Leave a comment