1

I have set up a simple project and when a post request is made, it is expected to return a response depending on what value the user entered.

I am testing my api logic in postman.

At the moment, no matter what value I enter, the same json response is sent back. This is not the expected logic.

views.py:

def function(request):
    if request.method == 'POST':
        if request.POST.get("number") == 1:
            print("Number is 1")
            return JsonResponse({'message':'Number is 1'})
        else:
            print("Number is not 1")
            return JsonResponse({'message':'Number is not 1'})

Even if the value of number is equal to 1, the message: Number is not 1, is returned.

Postman request:

{
    "number": 1
}

Thank You.

9
  • 1
    request.POST.get("number") == "1", not 1, but "1" Commented Oct 6, 2019 at 0:09
  • Hey @RossRodgers, I have tried to enter my data as a number and as a string as well, check my post, I have updated it. Thank You. Commented Oct 6, 2019 at 0:26
  • can you add a print(request.POST) at the beginning of your function and show us the result? Commented Oct 6, 2019 at 0:28
  • Hey @CalebGoodman the result is: <QueryDict: {}> Commented Oct 6, 2019 at 0:37
  • 1
    @ToanQuocHo classic case of needing to use request.body. request.POST is only used for your own views, and not for webhooks/postman. Commented Oct 6, 2019 at 0:52

1 Answer 1

1

From the docs:

If you need to access raw or non-form data posted in the request, access this through the HttpRequest.body attribute instead.

Since you are sending data that is "non-form" data, you need to use request.body instead:

import json

def function(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        if data.get("number", 0) == 1:
            print("Number is 1")
            return JsonResponse({'message':'Number is 1'})
        else:
            print("Number is not 1")
            return JsonResponse({'message':'Number is not 1'})
Sign up to request clarification or add additional context in comments.

3 Comments

Hey @CalebGoodman, I have tried to enter my data as a number and as a string as well, check my post, I have updated it. Thank You.
Hey @CalebGoodman Thank you bro this has solved the problem. One question, in the line: data.get("number", 0) Why is the second argument used, and what is it's purpose?
@nazam007 it is a default argument in case data doesn't have the number keyword. if you try to run data.get('key') when key doesn't exist, you will get an error unless .get has a default.

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.