views:

439

answers:

2

Let me explain what I'm trying to do, and if someone could point the correct way to do it & a solution to where I'm stuck that would be great !

Someone types url

www.ABC.com/showItem/Blackberry

I lookup "Blackberry" in my database and find data for it, now I want to show its details one a page.

Hence in the View I do this

return_data=simplejson.dumps(response_dict)

return render_to_response('workmodule/show_item_details.html', {"item_complete_data": return_data}, context_instance=RequestContext(request))

In myHTML I do this

data_from_django = {{ farm_complete_data }}

Question 1 : Is this the correct method to access the JSON data in the HTML ? Somehow I think there should be a better/cleaner way.

Question 2 : Another problem is all quotes are replaced with """ hence the javscript breaks. If above is the correct way, how to I "decode" the string correctly.

Note : I have used jquery's .ajax function earlier and it works great if you are on a page already and making a call to backend. The views in that case have returned the data in the same fashion as above & the data wasn't escaped. Or so it seemed by the time my ajax success: or error: functions handled it.

Thanks for taking time to look at this.

+1  A: 

Question 1: that's about right, actually.

Question 2: Don't decode it, pipe it to safe: {{farm_complete_data|safe}} so it doesn't try to html-escape it for you.

Yoni Samlan
Thanks Yoni ! That worked. This is good since I'm loading from db. What if it was unsafe ? Just asking.
PlanetUnknown
A: 

Why pass it to a template at all? You just want the JSON, so in the view, do this:

return simplejson.dumps(response_dict)

Then there's no need to worry about encoding/quoting.

Daniel Roseman
Well, this is just data. I need to format it and show it, hence need to assign it to a javscript variable.
PlanetUnknown
That doesn't make sense. If you're doing the formatting in a Django template, why convert it to JSON at all? But if you're sending it via an Ajax call, the Javascript will be doing the formatting and displaying.
Daniel Roseman
Maybe I didn't explain it correctly. This load of data that the view sends back is a whole lot of information. Its a pretty complex object. I haven't used dJangos templating system but in either case, this complex object will be used a number of times in the page lifecycle. It can be edited, the changes can be discarded to the original or ultimately saved. Its not a simple rendering. I will look at django templates as well, to see if this can be done in another way. Please let me know if you think my approach is incorrect. Thanks, I really appreciate your eyes on this.
PlanetUnknown