Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django rest framework find url kwarg in APIView

I have a url that looks like this:

url(r'^client_profile/address/(?P<id>.+)/$', views.ClientProfileAddressView.as_view())

And an APIView:

class ClientProfileAddressView(APIView):

    renderer_classes = (JSONRenderer,)
    permission_classes = (IsAuthenticated,)

    def put(self, request):
          ....

    def get(self, request):
          ....

In both put and get, I need to access the id url kwarg, the first one to update the object, the second to update it. How can I access the url argument in those methods?

like image 295
Alejandro Veintimilla Avatar asked Sep 23 '16 23:09

Alejandro Veintimilla


People also ask

What is APIView in DRF?

Function-based Views @api_view is a decorator that converts a function-based view into an APIView subclass (thus providing the Response and Request classes). It takes a list of allowed methods for the view as an argument. Curious how DRF converts function-based views into APIView subclasses?

What is difference between APIView and GenericAPIView?

APIView is a base class. It doesn't assume much and will allow you to plug pretty much anything to it. GenericAPIView is meant to work with Django's Models. It doesn't assume much beyond all the bells and whistles the Model introspection can provide.

What is @api_view in Django?

APIView class is a subclass of a Django View class. APIView classes are different from regular View classes in the following ways: Requests passed will be REST framework's Request instances, not Django's HttpRequest instances. Handler methods may return REST framework, instead of Django's HttpResponse.

What is Queryset in Django REST framework?

The root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects. The default behavior of REST framework's generic list views is to return the entire queryset for a model manager.


1 Answers

This should work:

def put(self, request, *args, **kwargs):
      id = kwargs.get('id', 'Default Value if not there')

def get(self, request, *args, **kwargs):
      id = kwargs.get('id', 'Default Value if not there')
like image 121
erik-sn Avatar answered Sep 22 '22 06:09

erik-sn