Is it possible to get the current user in a model serializer? I\'d like to do so without having to branch away from generics, as it\'s an otherwise simple task that must be done
I had a similar problem - I tried to save the model that consist user in, and when I tried to use
user = serializers.StringRelatedField(read_only=True, default=serializers.CurrentUserDefault())
like on official documentation - but it throws an error that user is 'null'
. Rewrite the default create
method and get a user from request helped for me:
class FavoriteApartmentsSerializer(serializers.ModelSerializer):
user = serializers.StringRelatedField(read_only=True, default=serializers.CurrentUserDefault())
class Meta:
model = FavoriteApartments
exclude = (
'date_added',
)
def create(self, validated_data):
favoriteApartment = FavoriteApartments(
apartment=validated_data['apartment'],
user=self.context['request'].user
)
favoriteApartment.save()
return favoriteApartment