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
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'),
]
The problem is:
urlpatterns = [
path('home/', views.BookCreate, name='homepage'),
]
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"
OK, All done!
Top comments (0)