1👍
✅
Because you’ve overridden the user
field and set it to read_only=True
, you cannot set a user when you’re creating/updating a model.
If you just need the user’s username, I’d suggest you to add a username
field into MessageSerializer
directly instead:
class MessageSerializer(serializers.ModelSerializer):
username = serializers.CharField(source='user.username', read_only=True)
class Meta:
model = Message
fields = '__all__'
Now you’ll get this payload instead:
{
"id": 1,
"user": 1,
"username": "timi",
...
And you should be able to set a user id now.
Source:stackexchange.com