[Answered ]-How to save the current user for the created model object in Django rest framework

1👍

✅

You can use permission decorator with IsAuthenticated permission to allow only the authenticated users as the following:

from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def create(request):
if request.method == 'POST':
    serializer = ArticleSerializer(data = request.data)

    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)

return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST)

The above code will allow only the authenticated users to use that view now to take the value of the user id from the logged-in user directly without sending it in the body request you can do the following:

from rest_framework import serializer
from .models import Article

class ArticleSerializer(serializers.ModelSerializer):

    class Meta:
        model = Article
        fields = '__all__'
        read_only_fields = ['author']

    def create(self, validated_data):
        # Get the authenticated user from the request
        user = self.context['request'].user

        # Add the authenticated user as the author of the article
        validated_data['author'] = user

        # Create the article with the updated data
        return super().create(validated_data)

Leave a comment