How to get the param PK in django restframework permission?

Question:

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.

Asked By: Jonathan Aplacador

||

Answers:

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.

Answered By: dichter

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

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}

Answered By: Druta Ruslan