Search code examples
djangodjango-rest-frameworkparametersrestful-url

With Django REST framework, how do I parse a RESTful string parameter?


I'm using Python 3.9 with

Django==3.1.4
djangorestframework==3.12.2

I want to pass a restful param ("author" string) to my GET method. In my urls.py file I have

urlpatterns = [
    ...
    path('user/<str:author>', views.UserView.as_view()),

And then in my UserView class (defined in my views.py file), I have

class UserView(APIView):
    def get(self, request):
        ...
        author = self.kwargs.get('author', None)

but when i execute

GET http://localhost:8000/user/myauthor

I get the error

TypeError: get() got an unexpected keyword argument 'author'

What else do I need to do to properly access my RESTful param in the URL?


Solution

  • To use the path params added in the url pattern, you must add the **kwargs as an extra parameter to the get() method. Your view should look like this:

    class UserView(APIView):
        def get(self, request, **kwargs):
           ...
           author = kwargs.get('author', None)