3

I am POST-ing to a view in Django. The POST body contains data in the following format :

{
    'Service' : 'API'
}

and I am doing this in my view :

args = request.POST
service = args.get('Service', '').strip()

But service comes out as ''

I used pdb and request.POST is like this :

<QueryDict: {u"{\n    'Service' : 'API'\n}": [u'']}>

Thats the reason service becomes '' because it has become a dict-in-a-dict. I want to know is this supposed to happen? What is the [u'']. From where does it get added in to the body? If it is something that should happen, how do I parse the body to get out Service?

Indradhanush Gupta
  • 4,067
  • 10
  • 44
  • 60

1 Answers1

1

if you're posting a string like that (common for things like JSON-RPC), vs using a known format (like multipart/form-data), you can use this (in your view):

def post(self, request, *args, **kwargs):
    body = request.body  # This is your string
    data = json.loads(body)
    service = data['Service']

This is predicated on your front-end code posting valid JSON data back. Otherwise, you'll be left to your own devices to decode something less standard (your example uses single quotes, for instance - not valid JSON). Encode a JavaScript object into JSON using JSON.stringify(my_obj), then post that value.

orokusaki
  • 55,146
  • 59
  • 179
  • 257