I've tried something like this, it does not work.
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
def save(self):
user = self.context['request.user']
title = self.validated_data['title']
article = self.validated_data['article']
I need a way of being able to access request.user from my Serializer class.
You cannot access the
request.user
directly. You need to access the request object, and then fetch the user attribute.Like this:
Or to be more safe,
More on extra context can be read here
As Igor mentioned in other answer, use can use CurrentUserDefault. If you do not want to override save method just for this, then use doc:
Actually, you don't have to bother with context. There is a much better way to do it: