I am developing a website which is build on 2 servers: Django(back), ReactJS(front); (I have changed some titles to abstract names for the sake of convenience)


class Model(model.Model):
    attr1 = models.CharField(max_length=500)
    attr1 = models.CharField(max_length=500)
    **author = models.ForeignKey(UserModel, on_delete=models.CASCADE)**

Custom Create View:

class ModelCreateAPI(APIView):
    def post(self, request):
        serializer = serializers.ModelSerializer(data=request.data)   
        if serializer.is_valid(raise_exception=True):
            model_saved = serializer.save()
        return Response({"success": "Model created successfully"})


class ModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Model
        fields = '__all__'

On my React APP there is a form that sends HTTP request, including 'user token', that is stored in localStorage. However, 'author' of model should be an integer that represents pk. I have managed to convert token to pk:

>>> from rest_framework.authtoken.models import Token
>>> Token.objects.get(key='token').user_id

Is it an effective way of doing this operation? What are your suggestions? How I can implement HTTP POST request in way that it saves the model with correct author_id?

0 Answers