Home » Django & REST Api » Solved: __init__() takes 1 positional argument but 2 were given

Solved: __init__() takes 1 positional argument but 2 were given

As we have seen previously, Django Rest Framework supports writing of views in two ways, 1. Function based views and 2. Class based views.

As we seen in our previous post “Developing REST API using functions in DRF application views” , we should how you can write the views using functions. Now, when we tried to change the same code for views from that post to write the views based on class, we got the following error,

TypeError at /user/1/

__init__() takes 1 positional argument but 2 were given

Solution :

For writing views based on functions, we had written the “urlpattern” in helloproject/helloapp/urls.py as,

urlpatterns = [
    path('user/<int:pk>/', views.user_by_pk),
]

So, when we tried to change the existing views based on function to views based on class, we completed modifying views.py but forgot to modify urls.py and run the server, and at the same time we got the error.

Hence as solution, we needed to change urlpatten from helloproject/helloapp/urls.py to add “.as_view()” to specifically mention we are using class based views.

urlpatterns = [
    path('user/<int:pk>/', views.user_by_pk.as_view()),
]

Subscribe our Rurban Life YouTube Channel.. "Rural Life, Urban LifeStyle"

Leave a Comment