Look at django-argonauts https://github.com/fusionbox/django-argonauts
It provides a nice (safe) template tag you can use to filter json serializable python objects into safe javascript objects. On Thursday, April 9, 2015 at 11:50:50 AM UTC-6, Eric Plumb wrote: > > Hi Djangoers! > > Sometimes in the course of human events it becomes necessary to encode a > JSON object directly into a template. We all prefer AJAX and REST APIs and > the rest of the TOFLAs, but in the cases where it has to be part of the > template, I'm wondering if there's an accepted canonical best-practice way > to do so and remain safe from XSS attacks and other nastiness. > > I'm aware of the following two methods: > > 1. HTML attribute loaded by jQuery's $.data() > > # view > return { ... {'my_obj': mark_safe(escape(json.dumps(obj))) } ... } > > # template > <div data-my-object={{ my_obj }}>...</div> > > # JS > var myObj = $('div').data('my-object'); // implicitly calls JSON.parse() > on the encoded object > > 2. Explicitly parsed JS object > > # view > return { ... {'my_obj': mark_safe(escapejs(json.dumps(obj))) } ... } > > # template > <script> > var myObj = JSON.parse('{{ my_obj }}') > </script> > > Are there better methods? It seems like this ought to come up often in > building safe websites, but I don't see a consensus out there on the Web. > Thanks in advance for your consideration! > > Eric > -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/7e3f929f-c2c2-405d-bd76-327939f2ce78%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.