0
votes

I have a django based website with user profiles system where users can add notes. I am trying to implement CRUD via REST Framework. I followed this tutorial:

https://dev.to/nobleobioma/build-a-crud-django-rest-api-46kc

I have modified the code. I have a model named Note, here is the model's code:

class Note(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="notes")
type = models.IntegerField(choices=NOTE_TYPE, default=0)
updated_on = models.DateTimeField(auto_now=True)
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)

class Meta:
    ordering = ["-created_on"]

The view class is as following:

@api_view(["POST"])
@permission_classes([IsAuthenticated])
@csrf_exempt
def add_note(request):
    payload = json.loads(request.body)
    user = request.user.id
    note = Note.objects.create(
        type=payload["type"],
        content=payload["content"],
        author=user,
)
serializer = NoteSerializer(note)
return JsonResponse({'notes': serializer.data}, safe=False, status=status.HTTP_201_CREATED)

When I run the server, all the other URLs work but the URL linked to this class gives me the following error:

raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

It seems like the error is evoked by the line:

payload = json.loads(request.body)

I have tried many solutions on similar error but nothing seems to help.

Here's the serializer:

class NoteSerializer(serializers.ModelSerializer):
class Meta:
    model = Note
    fields = ['type', 'content']
1
Can you share serializers.py file? And can you share the content of serializer.data? - Deniz Kaplan
thanks for pointing that out, I have edited the post. - user2202738

1 Answers

1
votes

Update you view(as you are using function based view), lets django rest framework to take care of your data's serialization and deserialization.

@api_view(["POST"])
@permission_classes([IsAuthenticated])
@csrf_exempt
def add_note(request):
    data = request.data
    user_id = request.user.id
    user = User.objects.get(id=user_id)
    serializer = NoteSerializer(data=data)
    if serializer.is_valid():
       serializer.save(author=user)
       return Response(serializer.data, status=status.HTTP_201_CREATED)
   return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

now try, you will get your desired output.