Search code examples
djangodjango-rest-frameworkdjango-generic-views

How to fix TypeError when using django-restframework-generics


I am learning how to use class-based generic views but I keep getting a type error

from invoice.models import Invoice
from invoice.serializers import InvoiceSerializer
from rest_framework import generics


class InvoiceList(generics.ListCreateAPIView):
    queryset = Invoice.objects.all()
    serializer_class = InvoiceSerializer


class InvoiceDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Invoice.objects.all()
    serializer_class = InvoiceSerializer

serialzers.py
from rest_framework import serializers

from .models import Invoice


class InvoiceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Invoice
        fields = "__all__"

urls.py
from django.urls import path
from invoice import views
from rest_framework.urlpatterns import format_suffix_patterns

urlpatterns = [
    path('invoice/', views.InvoiceList),
    path('invoice/<int:pk>/', views.InvoiceDetail),
]

urlpatterns = format_suffix_patterns(urlpatterns)

I get a type error with the message "init() takes 1 positional argument but 2 were given"


Solution

  • Your import in urls.py looks wrong. In urls.py, try something like this:

    from django.urls import path
    from .views import InvoiceList
    
    path('invoice/', InvoiceList.as_view(), name="invoice"), # name can be anything you want.   
    

    I never used the format_suffix_patterns, so you can try to take off that line to see if it works.