How to get Request.User in Django-Rest-Framework serializer?
You cannot access the request.user
directly. You need to access the request object, and then fetch the user attribute.
Like this:
user = self.context['request'].user
Or to be more safe,
user = Nonerequest = self.context.get("request")if request and hasattr(request, "user"): user = request.user
More on extra context can be read here
Actually, you don't have to bother with context. There is a much better way to do it:
from rest_framework.fields import CurrentUserDefaultclass PostSerializer(serializers.ModelSerializer): class Meta: model = Post def save(self): user = CurrentUserDefault() # <= magic! title = self.validated_data['title'] article = self.validated_data['article']
As Igor mentioned in other answer, you can use CurrentUserDefault. If you do not want to override save method just for this, then use doc:
from rest_framework import serializersclass PostSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) class Meta: model = Post