Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django error __init__() takes 1 positional argument but 2 were given

I'm currently making a simple get/post api with django 2.1. After i run the server and go to the .../article/ url it return an error

init() takes 1 positional argument but 2 were given

TRACE BACK:

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/article/

Django Version: 2.1
Python Version: 3.6.5
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'rest_framework',
 'api.apps.ApiConfig']
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 "C:\Users\admin\Miniconda3\lib\site-packages\django-2.1-py3.6.egg\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "C:\Users\admin\Miniconda3\lib\site-packages\django-2.1-py3.6.egg\django\core\handlers\base.py" in _get_response
  126.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\admin\Miniconda3\lib\site-packages\django-2.1-py3.6.egg\django\core\handlers\base.py" in _get_response
  124.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\admin\Miniconda3\lib\site-packages\django-2.1-py3.6.egg\django\views\decorators\csrf.py" in wrapped_view
  54.         return view_func(*args, **kwargs)

File "C:\Users\admin\Miniconda3\lib\site-packages\django-2.1-py3.6.egg\django\views\generic\base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)

File "C:\Users\admin\Miniconda3\lib\site-packages\rest_framework\views.py" in dispatch
  483.             response = self.handle_exception(exc)

File "C:\Users\admin\Miniconda3\lib\site-packages\rest_framework\views.py" in handle_exception
  443.             self.raise_uncaught_exception(exc)

File "C:\Users\admin\Miniconda3\lib\site-packages\rest_framework\views.py" in dispatch
  480.             response = handler(request, *args, **kwargs)

File "C:\Users\admin\Desktop\crawler\api\views.py" in get
  13.         article_serializer = ArticleSerializer(article, many=True)

Exception Type: TypeError at /article/
Exception Value: __init__() takes 1 positional argument but 2 were given

My models.py

from django.db import models
# Create your models here.
class Article(models.Model):
    class Meta:
        verbose_name_plural = "Article"
        verbose_name = "Article"

    id = models.ForeignKey('ArticlePicture', on_delete=models.CASCADE,primary_key=True)
    type = models.CharField(max_length=256, null=True)
    name = models.CharField(max_length=256, null=True)
    title = models.CharField(max_length=256, null=True)
    address = models.TextField(null=True)
    city = models.CharField(max_length=256, null=True)
    price = models.CharField(max_length=256,null=True)
    area = models.CharField(max_length=256,null=True)
    description = models.TextField(null=True)
    sell_date = models.TextField(null=True)
    expired_date = models.TextField(null=True)
    website = models.ForeignKey('Website', on_delete=models.CASCADE,default=1)
    website_uuid = models.CharField(max_length=256, null=True)
    seller_name = models.CharField(max_length=256, null=True)
    seller_address = models.CharField(max_length=256, null=True)
    seller_phone = models.CharField(max_length=256, null=True)
    seller_mobile = models.CharField(max_length=256, null=True)
    seller_email = models.CharField(max_length=256, null=True)
    seller_picture = models.TextField(null=True)
    project_name = models.CharField(max_length=256,null=True)
    project_investor = models.CharField(max_length=256,null=True)
    extended_data = models.TextField(null=True)

    def __str__(self):
         return self.id
class Website(models.Model):
    class Meta:
        verbose_name_plural = "Website"
        verbose_name = "Website"

    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=256,null=True)
    url = models.TextField(null=True)

    def __str__(self):
        return self.id
class ArticlePicture(models.Model):
    class Meta:
        verbose_name_plural = "ArticlePicture"
        verbose_name = "ArticlePicture"

    id = models.AutoField(primary_key=True)
    article_id = models.ForeignKey(Article, on_delete=models.CASCADE)
    url = models.TextField(null=True)

    def __str__(self):
        return self.id

VIEWS.PY :

from rest_framework import serializers
from rest_framework import serializers, viewsets, status
from rest_framework.response import Response
from django.contrib import admin, auth
from .serializers import ArticleSerializers, ArticlePictureSerializers
from .models import Article, ArticlePicture
from rest_framework.views import APIView
from django.http import Http404
from django.shortcuts import render
class ArticleSerializer(APIView):
    def get(self, request):
        article = Article.objects.all()
        article_serializer = ArticleSerializer(article, many=True)
        return Response(article_serializer.data)
    def post(self, request):
        article_serializers = ArticleSerializer(data = request.data)
        if article_serializers.is_valid():
            article_serializers.save()
            return Response(article_serializers.data, status=status.HTTP_201_CREATED)
        return Response(article_serializers.errors, status=status.HTTP_400_BAD_REQUEST)
class ArticlePictureSerializer(APIView):
    def get(self, request):
        article_picture = ArticlePicture.objects.all()
        article_picture_serializer = ArticlePictureSerializers(article, many=True)
        return Response(article_picture_serializer.data)
    def post(self, request):
        article_picture_serializers = ArticlePictureSerializers(data = request.data)
        if article_picture_serializers.is_valid():
            article_picture_serializers.save()
            return Response(article_picture_serializers.data, status=status.HTTP_201_CREATED)
        return Response(article_picture_serializers.errors, status=status.HTTP_400_BAD_REQUEST)  

SERIALIZERS.PY :

from rest_framework import serializers
from .models import Article, ArticlePicture
class ArticleSerializers(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = '__all__'
class ArticlePictureSerializers(serializers.ModelSerializer):
    class Meta:
        model = ArticlePicture
        fields = '__all__'

and my URLS.PY :

from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include
from api import views
from rest_framework.urlpatterns import format_suffix_patterns
from rest_framework import routers
urlpatterns = [
    path('admin/', admin.site.urls),
    path('article/',views.ArticleSerializer.as_view()),
    path('articlepic/',views.ArticlePictureSerializer.as_view()),
]
urlpatterns = format_suffix_patterns(urlpatterns)

I had added .as_view() after the path and it still returned, i'm still trying to figure out what i did wrong.

like image 413
Zerontelli Avatar asked Sep 26 '18 02:09

Zerontelli


1 Answers

You have the same name for view and serializer, try to rename view class, for example:

VIEWS.PY :

...
class ArticleAPI(APIView):
    def get(self, request):
        article = Article.objects.all()
        article_serializer = ArticleSerializer(article, many=True)

...
like image 186
Alex Lisovoy Avatar answered Sep 30 '22 19:09

Alex Lisovoy