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
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.
- [Django]-Django container can't access postgres container
- [Django]-How can I rename an uploaded file on Django before sending it to amazon s3 bucket?
- [Django]-Cache for everybody except staff members
- [Django]-How to get tests coverage using Django, Jenkins and Sonar?
- [Django]-How to fix "Failed to restart gunicorn.service: Unit gunicorn.socket not found." error?
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)
- [Django]-Django auto logout and page redirection
- [Django]-How to serve django static files on heroku with gunicorn
- [Django]-Django multi-tenant
- [Django]-Django template for loop and display first X matches
0π
perform_create is in the CreateModelMixin, your view should be a subclass of generics.ListCreateAPIView
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.