0

I have Comment model relationship with User

Like this Model

class Comment(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    comment = models.CharField()
    type = models.CharField()
    point = models.CharField()

Serializer

class CommentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Card
        fields = ['comment', 'type', 'point']

From here I already get the API response, to save in the comment model

def save_response_data(data):
    # here validate...
    json_data = {}
    # I want the user instance that is making the request
    serializer = CommentSerializer(data=json_data)

    if serializer.is_valid():
      serializer.save()

    return json_data

views request api

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    ...
    ...

    def post(self, request):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response(serializer.data, status=...)
    
    # Overwrite create method
    def create(self, request, *args, **kwargs):
        super(UserViewSet, self).create(request, args, kwargs)
        
        # Currently, this is how I am obtaining the user who makes the request
        user_id = request.user.id
        # Simple queryset build payload to send api
        payload = build_payload(user_id)

        response = requests.post(url, data=payload) 

        data = response.json()

        save_response_data(data)

I want the user instance that is making the request

I tried to do it with signals but it doesn't work, any idea or comment, it would be helpful

2
  • Can you share the code for the view that catches the request? Commented Nov 20, 2020 at 22:19
  • @HuLuViCa I edited the question Commented Nov 20, 2020 at 22:37

1 Answer 1

1

hi i use APIView and with that i can access auth user

class UserView(APIView):
    permission_classes = (IsAuthenticated)
    authentication_classes = (TokenAuthentication,)

    def post(self, request):
        user = request.user
        ...
        request.data['user']=user
        CommentSerializer(request.data)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.