Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access named url arguments in permissions with Django REST Framework?

I have an url config like

url(r'^user/(?P<id>[0-9]+)/$', UserView.as_view())

And a view class like

class UserView(GenericAPIView):
    serializer_class = UserSerializer
    permission_classes = [MyCustomPermission]

    def get(self, request, id):
        # code...

The permission is like

class MyCustomPermission(BasePermission):
    def has_permission(self, request, view, *args, **kwargs):
    # code

How do I access id in MyCustomPermission? I can't find it from the request or from *args or *kwargs. Documentation doesn't say anything about this. I've tried to look the source code but can't find how to access those named url arguments. Is it even possible?

like image 457
Masza Avatar asked Nov 15 '17 10:11

Masza


3 Answers

you can access from the view.kwargs.

like image 121
aman kumar Avatar answered Oct 16 '22 04:10

aman kumar


You can find them in:

request.resolver_match.kwargs.get('attribute_name')
like image 23
Nadhem Maaloul Avatar answered Oct 16 '22 03:10

Nadhem Maaloul


This is the wrong approach. Rather than trying to access keyword arguments there, you should be using object-level permissions and checking has_object_permission in your permission class.

like image 32
Daniel Roseman Avatar answered Oct 16 '22 02:10

Daniel Roseman