[Django]-Rest Framework Tutorial IntegrityError creating snippets

5πŸ‘

βœ…

I was running through this tutorial tonight and hit the same error. It seems the tutorial is a version or so behind the actual framework maybe? Regardless, I was able to get snippets to save after a bit of research.

Where the tutorial says to do this:

def perform_create(self, serializer):
    serializer.save(owner=self.request.user)

I switched to this:

def pre_save(self, snip):
    snip.owner = self.request.user

It seems that that perform_create method no longer exists or is called, so the owner never gets set, thus the error we saw. I’m not sure if what I did is the correct way of solving the problem, but it seems to work!

Here’s a link to the docs where I figured the above out: http://www.django-rest-framework.org/api-guide/generic-views/#genericapiview

πŸ‘€veddermatic

10πŸ‘

It seems that the answer depends on the Django REST framework version. Answer below has been tested on versions 3.2.4 and 3.10.3. If you are using these versions and class based views, you should put:

serializer.save(owner=self.request.user)

instead of

serializer.save()

in SnippetList.post() method, so that it looks as follows:

def post(self, request, format=None):
    serializer = SnippetSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save(owner=self.request.user)
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

The function pre_create() should be excluded from the SnippetList class.

πŸ‘€Nexy

2πŸ‘

you can update the save() parameters in the post method for the SnippedList:

def post(self, request, format=None):
    serializer = SnippetSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save(owner=self.request.user)
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
πŸ‘€Saber Alex

0πŸ‘

perform_create is in the CreateModelMixin, your view should be a subclass of generics.ListCreateAPIView

πŸ‘€Shen Wei

0πŸ‘

I have the same issue. I figured out that I add a perform_create method to SnippetSerializer but it need to be added in SnippetList view, it is described in tutorial.

Leave a comment