mahyard
mahyard

Reputation: 1238

How can I post params to be used as an object in Django

I want to send an ajax Post request to my server with a param to be used like an object:

student_name = request.data.get('student_info', {}).get('name')

When I send the params like this:

student_info: {"name":"Tom", "age": 20}

It produce the following error:

AttributeError: 'unicode' object has no attribute 'get'

The best answer is what I don't need to change my back-end, and solve my problem by sending data properly.

Regards,

Upvotes: 0

Views: 148

Answers (4)

user3677687
user3677687

Reputation:

You should send a JSON Object from your client. Set

Content-Type: application/json

in your request header and write your Object in the request body like so:

{"student_info":{"name":"Tom", "age": 20}}

Then you will directly get an object.

As easy as that :)

Upvotes: 1

Sijan Bhandari
Sijan Bhandari

Reputation: 3051

I hope you did stringify your data at the front-end. I once solved this problem by sending data from ajax as follows:

var js = {"name":"nguyen","age":"1"};
$.post("/", {'data': JSON.stringify(js)}, function(ret){
        console.log(ret)
    });

Upvotes: 1

zaidfazil
zaidfazil

Reputation: 9235

The request.data is just a string when posted from the front-end.

You could just do,

student_name = request.data.get('student_info', {})['name']

You could also do,

import json
student_name = json.loads(request.data.get('student_info')).get('name')

But, this may raise error if there is no student_info in request.data

Previous answer was a mistake from my side. Apologies from my behalf for that.

Upvotes: 1

MaximeK
MaximeK

Reputation: 2061

You need to send Json content and not key string values :

data: JSON.stringify({"student_info":"{'name':'Tom', 'age': 20}'})

your error is request.data.get('student_info', {}) return a string so you cannot retrieve the name with get('name')

And json.loads(request.data.get('student_info', {})) in Django part :)

Upvotes: 1

Related Questions