I am develop a simple rest api using Django 1.10 When I run my server and call app url I get an error:
TypeError:
__init__()
takes 1 positional argument but 2 were given
GET /demo/ HTTP/1.1" 500 64736
Environment:
Request Method: GET
Request URL: http://localhost:8000/demo/
Django Version: 1.10.4
Python Version: 3.5.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mydemoapp',
'rest_framework']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/home/aqib/DjangoProject/mydemoenv/lib/python3.5/site- packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/home/aqib/DjangoProject/mydemoenv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/home/aqib/DjangoProject/mydemoenv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
Exception Type: TypeError at /demo/
Exception Value: __init__() takes 1 positional argument but 2 were given
from django.db import models
class ProfileModel(models.Model):
name = models.CharField(max_length=30, blank=False, default='Your Name')
address = models.CharField(max_length=100, blank=True)
contact = models.IntegerField()
def __str__(self):
return '%s %s' % (self.name, self.address)
from django.shortcuts import render
from rest_framework import viewsets
from mydemoapp.models import ProfileModel
from .serializers import ProfileSerializer
class ProfileView(viewsets.ModelViewSet):
profile = ProfileModel.objects.all()
serializer_class = ProfileSerializer
from .models import ProfileModel
from rest_framework import serializers
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = ProfileModel
fields = ('name', 'address', 'contact')
from django.conf.urls import url
from mydemoapp import views
urlpatterns = [
url(r'^$', views.ProfileView),
]
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^demo/', include('mydemoapp.urls')),
]
To solve this ” Typeerror: takes 1 positional argument but 2 were given ” is by adding self argument for each method inside the class. It will remove the error.
The Python "TypeError: takes 1 positional argument but 2 were given" occurs for multiple reasons: Forgetting to specify the self argument in a class method. Forgetting to specify a second argument in a function's definition. Passing two arguments to a function that only takes one.
The Python "TypeError: __init__() missing 1 required positional argument" occurs when we forget to provide a required argument when instantiating a class. To solve the error, specify the argument when instantiating the class or set a default value for the argument. Here is an example of how the error occurs.
Positional Arguments An argument is a variable, value or object passed to a function or method as input. Positional arguments are arguments that need to be included in the proper position or order. The first positional argument always needs to be listed first when the function is called.
This very silly mistake I do too often. This is because of the urls.py(Application).
Always remember to call the .as_view()
method
Wrong
urls.py
from django.conf.urls import url
from mydemoapp import views
urlpatterns = [
url(r'^$', views.ProfileView),
]
Correct
urls.py
from django.conf.urls import url
from mydemoapp import views
urlpatterns = [
url(r'^$', views.ProfileView.as_view()),
]
You are using ViewSet
urls wrong. This is right way
# project/urls.py
from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from mydemoapp import views
router = routers.DefaultRouter()
router.register(r'demo', views.ProfileView)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include(router.urls)),
]
Read more http://www.django-rest-framework.org/api-guide/routers/
Answering comment
Now i get AssertionError: base_name argument not specified, and could not automatically determine the name from the viewset, as it does not have a .queryset attribute.
Your view is incorrect as well. It should spicify queryset
not profile
class ProfileView(viewsets.ModelViewSet):
queryset = ProfileModel.objects.all() # <-- here
serializer_class = ProfileSerializer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With