Home > Mobile >  Can I provide automatically current user in Django rest API like this?
Can I provide automatically current user in Django rest API like this?

Time:01-09

I have a Django rest api. In my model I have a user as a foreign key. When I do a post with the, I do not want that the user needs to provide his own user. But if the user does not provide his user credentials, the serializer won't be valid and then won't be saved. I have found that we can access to serialized dat before validation with initial_data so I am doing like this to save the user automatically from the token provided. The user need to provide everything except his own user. Is it ok or am I doing something not recommended ?

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def add_mesure(request):
    serializer = MesureSerializer(data=request.data)
    serializer.initial_data['user'] = request.user.id
    if serializer.is_valid():
        serializer.save()
    return Response(serializer.data) 

CodePudding user response:

As you are already taking the token as a form of user verification, hence you can omit the user field from serializer (otherwise user might put someone else's id for example) and then pass the request object to serializer to get user from it during saving. Like this:

#serializer
class MesureSerializer(ModelSerializer):
    class Meta:
        exclude = ['user',]
    ...
    def create(self, validated_data):
       validated_data['user'] = self.context['request'].user
       return super().create(validated_data)

Also, to pass the value of request, you can use context parameter of the serializer.

#view
serializer = MesureSerializer(data=request.data, context={'request':request})
  • Related