Monday, June 6, 2011

Re: Request and null value

On 2011-06-06, at 07:36 , Constantine wrote:
> 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?
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)

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate