Azima
Azima

Reputation: 4151

django post method create record using ListApiView

I am a beginner to django rest-framework and trying to create new record using POST method in ListAPIView.

Here's my serializer:

from scheme.models import ProjectScheme, ProjectSchemeMaster
from rest_framework import serializers

class SchemeDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = ProjectScheme
        fields = ('id', 'name', 'parent_scheme_id', 'rule', 'created_on', 'created_by', 'updated_on','updated_by')
        depth=1

And view:

class ProjectSchemeList(ListAPIView):
"""
List all Schemes
"""
serializer_class = SchemeDetailSerializer
# pagination_class = ProjectLimitOffsetPagination

def get_queryset(self, *args, **kwargs):
    comp_logger.info('invoked scheme list all')
    schemes = ProjectScheme.objects.all().order_by('-id')
    return schemes

def post(self, request, *args, **kwargs):
    if serializer_class.is_valid():
        serializer_class.save()
        return Response(serializer_class.data, status=status.HTTP_201_CREATED)
    return Response(serializer_class.errors, status=status.HTTP_400_BAD_REQUEST)

I get this error:

NameError at /scheme/schemes/
name 'serializer_class' is not defined

How do I pass request data to serializer_class?

Upvotes: 0

Views: 927

Answers (1)

Ozgur Akcali
Ozgur Akcali

Reputation: 5492

Created functioanlity is included by default in CreateAPIView generic view, or if you want to provide list and create functionality, you can use ListCreateAPIView which provides both. More details on DRF's generic views here.

class ProjectSchemeList(ListCreateAPIView):

    serializer_class = SchemeDetailSerializer

    def get_queryset(self, *args, **kwargs):
        comp_logger.info('invoked scheme list all')
        schemes = ProjectScheme.objects.all().order_by('-id')
        return schemes

With this definition, you won't need to manually write a post method.

If you want to manually define a post methdod, you can investiage how it is written in generic CreateAPIView and copy it, it's slighly different from how you want to write it. Finally, following is your version of the post method with errors fixed:

class ProjectSchemeList(ListAPIView):
    serializer_class = SchemeDetailSerializer

    def get_queryset(self, *args, **kwargs):
        comp_logger.info('invoked scheme list all')
        schemes = ProjectScheme.objects.all().order_by('-id')
        return schemes

    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Notice how we use self.serializer_class(data=request.data) instead of just serializer_class

Upvotes: 2

Related Questions