NILOTPAL GHOSH
NILOTPAL GHOSH

Reputation: 26

NameError in Django Rest Framework, it's showing my model name is not defined

I am trying to serialize the data from the database so that I can access the data on the client side apps. I am new to the Django for just 1 month. Kindly help me out. What is the correct method to execute this problem? I just want it to be generated in the data in JASON format. And it's giving me an error. What am I doing wrong here? Is this not the way?

This the error:

NameError at /api/jobcardJobcard-ViewSet/ name 'Jobcard' is not defined Request Method: GET Request URL: http://127.0.0.1:8000/api/jobcardJobcard-ViewSet/ Django Version: 2.2 Exception Type: NameError Exception Value:
name 'Jobcard' is not defined Exception Location: /vagrant/jobcard_api/views.py in list, line 16 Python Executable: /home/vagrant/beanalyticenv/bin/python3

I have tried this where Jobcard is my model name

from jobcard_api.models import Jobcard

then this gives a new error of NameError of

name 'JobcardSerializer' is not defined"

This is my models.py inside an app and the app is inside a project, there are three apps and all of them giving the same kind of error with different names

from django.db import models
class Jobcard(models.Model):
    """Database model for the jobcard"""
    id = models.AutoField(primary_key=True)
    jobcard_number = models.CharField(max_length=30, unique=True, blank=False), ..., observation = models.TextField(blank=True)
    def get_jobcard_number(self):
        """Retrieve jobcard number"""
        return self.equipment_name

This is my serializers.py inside an app called jobcard_api.

from rest_framework import serializers
from jobcard_api import models
class JobcardSerializer(serializers.ModelSerializer):
    """Serializer for the jobcard object"""
    class Meta:
        model = models.Jobcard
        fields = ('id', 'jobcard_number')
class DetailedJobcardSerializer(serializers.ModelSerializer):
    """Serializes the details of jobcard"""
    class Meta:
        model = models.Jobcard
        fields = ('id', 'jobcard_number',.., 'observation')
    def create(self, validated_data):
        """Create and return a new jobcard details"""
        jobcard = models.Jobcard.objects.create_jobcard(
            jobcard_number=validated_data['jobcard_number'],
            date_of_jobcard=validated_data['date_of_jobcard'],
            ..., observation=validated_data['observation']
        )
        return jobcard

This is my views.py inside an app called jobcard_api.

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import viewsets
from jobcard_api import serializers
from jobcard_api import models

class JobcardViewSet(viewsets.ViewSet):
    """Jobcard API ViewSet"""
    serializer_class = serializers.JobcardSerializer
    def list(self, request):
        """Returns a list of Data from databse"""
        jobcard_api = Jobcard.objects.all()
        serializer = JobcardSerializer(jobcard_api, many=True)
        return Response(serializer.data)
    def create(self, request):
        """Create new data in  databse"""
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(
                serializer.errors,
                status=status.HTTP_400_BAD_REQUEST
                )
    def retrieve(self, request, pk=None):
        """Handle updating an object"""
        return Response({'method':'PUT'})
    def update(self, request, pk=None):
        """Handle a partial update of an object"""
        return Response({'method':'PATCH'})
    def partial_update(self, request, pk=None):
        """Handle updating part of an object"""
        return Response({'http_method': 'PATCH'})
    def delete(self, request, pk=None):
        """Delete an object"""
        return Response({'method':'DELETE'})

This is my urls.py inside an app called jobcard_api.

from django.urls import include, path
from rest_framework.routers import DefaultRouter
from jobcard_api import views
from rest_framework import routers
router = routers.DefaultRouter()
router.register('Jobcard-ViewSet', views.JobcardViewSet, base_name='Jobcard-ViewSet')
urlpatterns = [
    path('', include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

Upvotes: 0

Views: 5164

Answers (1)

wencakisa
wencakisa

Reputation: 5958

You have mistake in your viewset's list method serializer accessing.

You may replace your direct JobcardSerializer(...) instance with self.serializer_class, since you already assigned in correctly in the serializer_class = ... assignment.

...

class JobcardViewSet(viewsets.ViewSet):
    serializer_class = serializers.JobcardSerializer

    def list(self, request):
        ...
        serializer = self.serializer_class(jobcard_api, many=True)

Upvotes: 0

Related Questions