0

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']
2
  • Can you share serializers.py file? And can you share the content of serializer.data? Commented May 19, 2020 at 2:45
  • thanks for pointing that out, I have edited the post. Commented May 19, 2020 at 3:29

1 Answer 1

1

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.

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

2 Comments

thank you! and if I want to save some fields dynamically and not through the API, how do I do that? For example, the author, as the author foreignkeyed to the user table, and it should be the logged in user.
see i have updated my answer, now you can create Note with logged in user.

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.