I am able to send JSON data from Django to my javascript function, but
I would like to iterate JSON by using the Django template language. Is
this possible at all?
For example, my view passing JSON back:
def ajax_form_test(request):
data = serializers.serialize("json", Order.objects.all())
if request.method == 'POST':
return HttpResponse(data, mimetype="application/json")
And my Javascript function that receives JSON:
function hello() {
var form_data = {
url: "/ajax_form_test/",
handleAs: "json",
load: function(data){
dojo.byId("myDiv1").innerHTML = data;
},
error: function(data){
alert("Holy Bomb Box, Batman! An error occurred: " +
data);
},
timeout: 5000,
form: "myForm"
};
dojo.xhrPost(form_data);
}
Right now the way my template displays JSON is by using innerHTML as
above. But I would like to convert the data somehow so that Django can
iterate in the {{...}} syntax.
Thanks,
robo
> I am able to send JSON data from Django to my javascript function, but
> I would like to iterate JSON by using the Django template language. Is
> this possible at all?
No, it's not. Javascript works on the client side and doesn't know
anything about the way the server did generate the response.
But nothing prevents you to iterate your data with regular javascript,
ie. stuff like :
for (i = 0; i < data.length; i++) {
// do something.
}
In this case, you may want to build your json object by hand with
simplejson.dumps() instead of using serializers.serialize(), it will
give you more flexibility.
Regards,
olivier
Can you give an example of what you are suggesting?
> One thing that you can do is to pass a
> render_to_response call a template and the python dictionary you want
> modified and let django work its majic on it before returning the
> '._container' to the page via json.
Thanks.
To Olivier: Iterating through javascript like that is possible, but it
poses a disadvantage in that I cannot access the data's related object
(e.g. ForeignKey relationships).
For example I can do data[0].fields.user and I'd get "3" as a
response, but I cannot do data[0].fields.user.username, where user is
a foreignkey. Whereas in Django I can do something like this:
manager.user.username and I'd get the user name.
Thanks for the responses, all.
That's the reason you may want to build a custom JSON dict and use
simplejson.dumps().
Something like:
orders_qs = Order.objects.all()
orders = []
for order in order_qs:
# stuff all the fields and foreign key fields you want to use
here.
item = [order.foo, order.spam, order.user.username]
orders.append(item)
output = {"orders" : orders}
return HTTPResponse(simplejson.dumps(output), mimetype = "application/
javascript")
and in javascript
var form_data = {
url: "/ajax_form_test/",
handleAs: "json",
load: function(data){
for (i = 0, i < data.orders.length, i ++) {
// Do something
}
},
I think I got the idea of your view. What I'd like to see is an
example of your template and javascript to see how you are accessing
the json data.
Thanks a lot,
robo
But meanwhile, I've tried to switch from serializers to simplejson,
and it's giving me a "Error: bad http response code:500" everytime,
whereas serializers give me the same error only 50% of the time (and
this too is BAD!).
When I'm using serializers, the only difference between getting an
error not depends on which objects I'm getting. For example, I get an
error when I use this code:
def ajax_form_test(request):
data = serializers.serialize("json", Order.objects.all())
return HttpResponse(data, mimetype="application/javascript")
but no errors when I use this code:
def ajax_form_test(request):
data = serializers.serialize("json", Manager.objects.all())
return HttpResponse(data, mimetype="application/javascript")
And when I use simplejson, I ALWAYS get errors no matter what. The
code is as simple as this:
def ajax_form_test(request):
data = Manager.objects.all()
return HttpResponse(simplejson.dumps(data), mimetype="application/
javascript")
Help me solve this bizzare mystery!
Thanks,
robo
Known to who? I'm not aware of any current Decimal serialization
issues, and a quick search of the ticket database didn't reveal
anything, either.
There were some decimal serialzation issues when 0.96 was released,
but they were fixed long ago, and the test suite includes Decimal (and
Float) serialization..
Can you either:
- provide an example that demonstrates your problem
- point at the Django ticket for the serialization issue you describe.
Yours,
Russ Magee %-)
Firstly, it's a "problem" with simplejson, not with Django. It would be
bad policy for us to make any changes to simplejson. We just include a
copy of the upstream simplejson source.
It's not even really a problem with simplejson, since Bob Ippolito has
designed it very well to make it easy to extend as you might wish.
That's exactly how we handle the problem in Django and how you should
handle it if you are using simplejson directly for your own purposes.
Regards,
Malcolm "
He hacked it so that any decimal field is returned as a string. All
you have to do to use this is paste the code into a file, such as
json.py, and import the json_encode function from that file where you
want to use it:
from dev_gfs.shop.json import json_encode
def hello():
return HttpResponse(json_encode(OrderDetail.objects.all()),
mimetype="application/javascript")
To Russel: you said that this decimal serialization issue was fixed a
long time ago. How so?
Thanks,
robo
s/Russel/Russell/ :-)
I'm not entirely sure what 'this decimal serialization issue' actually
is - this thread hasn't produced a clear test case that demonstrates
that there is a problem in Django's JSON serializer.
However, in 0.96, we didn't make the clear distinction between
Decimals and Floats that exists in SVN trunk. This caused all sorts of
problems for serialization.
SVN trunk now makes the distinction between the two types, and the
test suite contains explicit serialization tests for Floats and
Decimals of various levels of precision. If there is a test case we're
missing, feel free to open a ticket.
Yours,
Russ Magee %-)