Reputation: 123
I have this permission in Django that look like this:
class PermissionName(BasePermission):
def has_object_permission(self, request, view, obj):
if request.method in SAFE_METHODS:
return True
#I want to extract the pk or id params in here.
return False
Can anybody help me get the params of request I tried using self.kwargs["pk"]
, request.POST['pk']
but they all return saying object has no attribute.
Upvotes: 1
Views: 1290
Reputation: 7412
If you have only one pk
in your url and you use has_object_permission
then.
class PermissionName(BasePermission):
def has_object_permission(self, request, view, obj):
obj.pk # To get object id.
But what if you have more then two pk
in your url
urls.py
path("buildings/<int:pk>/units/<int:unit_pk>/")
Then you can get pk's
from view
attribute.
class PermissionName(BasePermission):
def has_object_permission(self, request, view, obj):
print(view.kwargs)
Results:
{'pk': 13, 'unit_pk': 71}
Upvotes: 2
Reputation: 416
lets say your path is:
path('listings/get/category/<str:pk>/', endpoints.HousesWithSameCategory.as_view()),
Your request: api/listings/get/category/1/
In your class method view use:
def get_queryset(self):
print(self.kwargs)
This will return {'pk': '1'}
self.kwargs
will return all your dynamic params
Upvotes: 1
Reputation: 49
If pk
is a parameter of the POST request, you can access it with request.POST.get('pk')
. In your post, you are not using get()
, so that could be the issue.
If the object is provided as an argument to the function, I'm assuming you want the ID of it. That can also be achieved with obj.id
.
Upvotes: 1