Search code examples
djangodjango-rest-frameworkdjango-viewsdjango-rest-framework-simplejwt

Where to set the author as request.user


Problem

In my model I have the field author which I want to enter as a ForeignKey with the UserModel with the user who has authenticated himself via JWT Token. My API and JWT authentication works fine, but I don't know where to set the author = request.user in the backend.


My Code:

apis.py

class AlarmstichworteCreateApi(ApiErrorsMixin, APIView):
    permission_classes = [IsAuthenticated]

    class InputSerializer(serializers.ModelSerializer):

        author = UserListAPI.OutputSerializer(source='UserListAPI_set', many=True)
        created = serializers.DateTimeField()
        updated = serializers.DateTimeField()
        name = serializers.CharField(max_length=100)
        class Meta:
            model = AlarmstichworteConfig
            fields = (
                '__all__'
            )

    def post(self, request, *args, **kwargs):
        serializer = self.InputSerializer(data=request.data)
#!      serializer = self.InputSerializer(data=request.data, author=request.user) # Try 1
        serializer.is_valid(raise_exception=True)

        create_alarmstichwort(**serializer.validated_data)
#!      create_alarmstichwort(**serializer.validated_data, author=request.user) # Try 1

        return Response(status=status.HTTP_201_CREATED)

services.py

def create_alarmstichwort(
    *,
    author: ForeignKey,
    created: datetime,
    updated: datetime,
    name: str,

) -> AlarmstichworteConfig:

    if AlarmstichworteConfig.objects.filter(id=id).exists():
        raise ValidationError('Alarmstichwort existiert bereits')

    alarmstichwort = AlarmstichworteConfig.objects.create(
        author=author,
        created=created,
        updated=updated,
        name=name,
    )
    alarmstichwort.full_clean()
    alarmstichwort.save()

    return alarmstichwort

I would be happy if anyone could help me. Many thanks in advance!


Solution

  • Thank you for the clarification in the comments. If you remove the author field from the serializer, then pass it in as a parameter to create_alarmstichwort as you tried earlier with the value coming from request.user, you'll get the results you'd like. This does mean you'll need to stop using fields = "__all__".