nyptop
nyptop

Reputation: 59

DRF: Functional view not returning Response as expected

In the Django Rest Framework, I am looking to have my view return a personalised message using the following line:

return Response({"Message":f"Post {pk} successfully {prefix}liked by {destination}"})

What I expect it to return:

{'Message': 'Post 130 successfully liked by 8'}

What is actually returned:

<Response [200]>

Why is this happening? How can I return the expected message?

Here is the full view if it helps:

@api_view(['POST'])
def like_view(request, pk, destination):
    #destination is the user_id
    post = Posts.objects.get(pk=pk)

    if post.is_expired == True:
        print("expired")
        return Response({"message":"post expired"})

    if check_self_action(destination,post):
        return Response({"message":"cannot like own post"})

    liked = check_like(destination, post)

    prefix = ""

    if liked:
        post.likes.remove(destination)
        prefix = "un"
    else:
        post.likes.add(destination) 

    return Response({"Message":f"Post {pk} successfully {prefix}liked by {destination}"})

Upvotes: 1

Views: 418

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

This is only what it prints when you print the message (call str(…) on it). The response contains the proper message.

If you for example work with the requests package, then you can obtain the JSON content with the .json() method [requests-doc]:

response = requests.post('www.some-domain.com/some/path/with/values')
print(response.json())

You can also access the response as binary content with the .content attribute [requests-doc]:

response = requests.post('www.some-domain.com/some/path/with/values')
print(response.content)

which will return a bytes object with the response, here thus a JSON blob.

Upvotes: 1

Related Questions