Django Permission Required
Solution 1:
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
classViewCompanyPermission(permissions.BasePermission):
defhas_permission(self, request, view):
ifnot request.user.has_perm('api.view_company'):
raise exceptions.PermissionDenied("Don't have permission")
returnTrue
and use it on your view via permission_classes
field:
classCompanyDetailView(APIView):
permission_classes = (ViewCompanyPermission, )
defget(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
defpermission_required(permission_name, raise_exception=False):
classPermissionRequired(permissions.BasePermission):
defhas_permission(self, request, view):
ifnot request.user.has_perm(permission_name):
if raise_exception:
raise exceptions.PermissionDenied("Don't have permission")
returnFalsereturnTruereturn PermissionRequired
Then you can use it like:
classCompanyDetailView(APIView):
permission_classes = (permission_required("api.view_company", raise_exception=True), )
# ...
Solution 2:
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/
Solution 3:
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
Post a Comment for "Django Permission Required"