PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, August 9, 2022

[FIXED] How to pass a decimal value when making a post request in django?

 August 09, 2022     decimal, django, django-rest-framework, json, python-3.x     No comments   

Issue

I am trying to make a post request to a third party application along with some data and the data also have a decimal value up to two points, which I am getting from database (order.amount) but after making the request getting error saying data is not serializable to json then i passed it as '"%s"' % round(order.amount,2) then also getting error post data is empty.Looking for suggestion to solve this problem.

    request = Transfer.request_transfer(beneId=beneficiary_id, amount=round((order.amount),2) 
    transferId=transfer_identifier,remarks="Test transfer")

    getting error: decimal is not json serializable

    print('"%s"' % round((order.amount),2) #"5000.23"
    
    request = Transfer.request_transfer(beneId=beneficiary_id, amount='"%s"' % round((order.amount),2) transferId=transfer_identifier,remarks="Test transfer")
    
    getting error : PreconditionFailedError: Reason = Post data is empty or not a valid JSON:: response = {"status": "ERROR", "subCode": "412", "message": "Post data is empty or not a valid JSON"}
    
    
    but when hardcoding amount then it is working
    request = Transfer.request_transfer(beneId=beneficiary_id, amount= "5000.23" transferId=transfer_identifier,remarks="Test transfer")

Solution

Pay attention to this line,

print('"%s"' % round((order.amount),2) #"5000.23"

I guess you miss one thing: you're formatting your decimal value, but you do this with quotes, so your variable amount will contain "5000.23" string instead of 5000.23.

So, look:

request = Transfer.request_transfer(beneId=beneficiary_id, amount='"%s"' % round((order.amount),2) transferId=transfer_identifier,remarks="Test transfer")

you have amount='"5000.23"' and these quotes get in the way of serialization.

To fix it, just remove the additional quotes:

print('%s' % round((order.amount),2) # '5000.23'

request = Transfer.request_transfer(beneId=beneficiary_id, amount='%s' % round((order.amount),2) transferId=transfer_identifier,remarks="Test transfer")


Answered By - Fedor Ivanov
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing