Request and null value

215 views
Skip to first unread message

Constantine

unread,
Jun 6, 2011, 1:36:47 AM6/6/11
to Django users
Hi, a have a problem, but may be this is expected behaviour:

on client side i'm post:
$.post("my url",{myvar:null}...)

but on server side:
request.POST becomes {myvar:u'null'}

null deserialized to string. So, do i need to report a bug in tracker?

Jani Tiainen

unread,
Jun 6, 2011, 1:50:43 AM6/6/11
to django...@googlegroups.com

It's not "deserialized" thus not a but but works as designed. HTTP
POST/GET parameters are only strings. Nothing more, nothing less. Django
doesn't do any magic by default.

You can use some known notation to handle your data, like JSON which can
serialize and deserialize data correctly.

--

Jani Tiainen

Constantine

unread,
Jun 6, 2011, 3:52:31 AM6/6/11
to Django users
Thanks, i've workaround this with empty string.
I was surprised when saw raw_post_data which looks very similar to GET
string. I confused this behaviour with JSON parser.

Masklinn

unread,
Jun 6, 2011, 4:07:18 AM6/6/11
to django...@googlegroups.com
Nope, this is normal behavior: the javascript value `null`, when converted to a string, becomes the string `"null"`. String conversion is exactly that $.post does with its POSTdata in the normal case of application/x-www-form-urlencoded. So Django gets a string in its POST value. Nothing to see here.

The alternative is to avoid using `application/x-www-form-urlencoded`, and instead use a JSON-encoded POST body. That's significantly more work on both sides, but it will allow you to send complete (typed) JSON data to your server.

On the JS side, you'll have to call $.ajax directly (rather than just $.post) using the following options:

$.ajax({
type: 'POST',
url: your-endpoint,
// This sets the POST body directly, to a JSON-encoded data structure
data: JSON.stringify(your_javascript_payload),
// jquery tries to convert your POST body through post-processing, tell it to leave your POST data as-is
processData: false,
// your callbacks
});

On the Django side, you will not be able to use request.POST. Instead, you'll have to go through `HttpRequest.raw_post_data` or to use HttpRequest as a file:

data = json.loads(request)
or
data = json.loads(request.raw_post_data)

Reply all
Reply to author
Forward
0 new messages