DEV Community

Serhat Teker
Serhat Teker

Posted on • Originally published at tech.serhatteker.com on

Django Class-Based View - TypeError

Error : Django 2.X Error: __init__() takes 1 positional argument but 2 were given

It took me significant amount of time to fix this issue. For future reference and possible-need of someone I would like to share the root cause and solution;

When you look at the console output you will the see traceback of the error like below:

Traceback (most recent call last):
  File "/home/user/projects/django-cbv/.venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
      response = get_response(request)
  File "/home/user/projects/django-cbv/.venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response
      response = self.process_exception_by_middleware(e, request)
  File "/home/user/projects/django-cbv/.venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
      response = wrapped_callback (request, *callback_args, **callback_kwargs)
TypeError: __init__() take s 1 positional argument but 2 were given
Enter fullscreen mode Exit fullscreen mode

It means you need to use as_view() at the end of class-based views when declaring in the urls:

# src/app/urls.py
from django.urls import path

from . import views


app_name = "app"
urlpatterns = [
    path('home/', views.BookCreate.as_view(), name='homepage'),
]
Enter fullscreen mode Exit fullscreen mode

The problem is:

urlpatterns = [
    path('home/', views.BookCreate, name='homepage'),
]
Enter fullscreen mode Exit fullscreen mode

It does not matter, it may be any CBV but for additional detail you can look at the view:

# src/app/views.py
from django.views.generic.edit import CreateView

from .models import Book


class BookCreate(CreateView):
    model = Book
    fields = ('name', 'isbn', 'author')
    template_name = "app/book_form.html"
Enter fullscreen mode Exit fullscreen mode

OK, All done!

Top comments (0)