4

In Django view, I am trying this-

@csrf_exempt
def customer_list(request):
    """
    List all customers, or create a new customer.
    """
    if request.method == 'GET':
        snippets = Customer.objects.all()
        serializer = CustomerSerializer(snippets, many=True)
        return JsonResponse(serializer.data, safe=False)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = CustomerSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)

On posting data from postman,I get

JSON parse error - Expecting value: line 1 column 1 (char 0)

2
  • 1
    If you're using DRF, why are you writing a plain Django view rather than a DRF one? At the very least you should decorate your function with api_view. Commented Oct 7, 2019 at 11:40
  • i am a django rest newbie, thanks for the info Commented Oct 7, 2019 at 11:43

1 Answer 1

4

The problem is that you are passing the entire request object to the JSON parser, instead of the body that contains the actual JSON content.

But you shouldn't do this yourself anyway. Let DRF do it for you.

from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view()
def customer_list(request):
    """
    List all customers, or create a new customer.
    """
    if request.method == 'GET':
        snippets = Customer.objects.all()
        serializer = CustomerSerializer(snippets, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = CustomerSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=201)
        return Response(serializer.errors, status=400)

Or even better, use a class-based view which literally includes all this functionality for you already:

from rest_framework import generics

class CustomerList(generics.ListCreateAPIView):
     model = Customer
     serializer_class = CustomerSerializer

That's all you need.

Sign up to request clarification or add additional context in comments.

1 Comment

To my surprise this snippet (is quite similar to OP's snippet) is working fine. In this snippet entire request object is parsed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.