Home > Software design >  Why I get an error when adding __init__(self) method to Django rest framework viewset class?
Why I get an error when adding __init__(self) method to Django rest framework viewset class?

Time:11-28

I Am keep getting a error when trying to build a Django API.

I have this class:

from uuid import UUID
from django.shortcuts import render
from django.http.response import JsonResponse
from django.http.request import HttpRequest
from rest_framework import viewsets, status
from rest_framework.parsers import JSONParser
from rest_framework.response import Response
from Instruments import serializers
from Instruments.services import InstrumentsService
from rest_framework.decorators import api_view
from Instruments.services import InstrumentsService
from Instruments.models import Instrument
from Instruments.serializers import InstrumentsSerializer


# Application views live here
class InstrumentViewSet(viewsets.ViewSet):
    # instruments = Instrument.objects.all()

    def __init__(self):
        # self.instrument_service = InstrumentsService()
        # self.instruments = Instrument.objects.all()
        super().__init__()

    def list(self, request: HttpRequest):

        try:
            self.instruments = Instrument.objects.all()
            serializer = InstrumentsSerializer(self.instruments, many=True)
            # data = self.instrument_service.get_instruments()
            data = serializer.data
            return JsonResponse(data, status=status.HTTP_200_OK, safe=False)
        except Exception as exc:
            return JsonResponse(
                {"Status": f"Error: {exc}"},
                status=status.HTTP_400_BAD_REQUEST,
                safe=False,
            )

when the init() method is defining even if it is just doing pass the django server gives me this error when I send a request:

TypeError at /api/
__init__() got an unexpected keyword argument 'suffix'

If I remove or comment out the init() method it works.why??

CodePudding user response:

The “got an unexpected keyword argument” exception is rather descriptive. What it means is your class instance (in this case, your ViewSet instance) was initialized with a keyword argument that you’re not handling. That can be fixed by doing the following in your init method:

def __init__(self, **kwargs):
    # self.instrument_service = InstrumentsService()
    # self.instruments = Instrument.objects.all()
    super().__init__(**kwargs)

This is required because the super class (View) utilizes **kwargs when the instance is initialized.

For the record, this is not using Django as it was intended. Django was never meant for service layers and using the init method like this is counterproductive since a ViewSet takes a queryset variable. I would encourage you to read the documentation much more thoroughly before continuing with this project of yours.

  • Related