[Django]-DRF how to save a model with a foreign key to the User object

6👍

When you’re correctly authenticated by token, then you should have a user attribute available in request object.

So depending where you add the logic for passing user object, you can have it in the generic view:

def perform_create(self, serializer):
    serializer.save(user=self.request.user)

or inside serializer (assuming your view is passing context):

def create(self, validated_data):
    data = validated_data.copy()
    data['user'] = self.context['request'].user

    return super(JournalSerializer, self).create(data)

0👍

This should work.

data = request.data
data['creator'] = user_id  # fetch user_id from metadata first
serializer = YourSerializer(data=data, partial=True)
if serializer.is_valid():
    serializer.save()

Please comment if you need any further clarification , or face any issues.

Leave a comment