Getting serialized json objects from django templates?

I need an explanation. If, for example, I make a view with a serialized object:

def sample(request): res = [{'name':'man'}] encoded = json.dumps(res) return render_to_response('sample/example.html',{'encoded':encoded} ) 

In my templates, I pass:

 {{encoded}} 

Now from the python script you can do:

 data = json.loads(urllib2.urlopen(url/to/site).read() 

It says ValueError: the JSON object cannot be decoded. But not a {{encoded}} json object? And if so, how do I get this?

thanks

+4
source share
2 answers

Try in the template:

 {% autoescape off %} {{ encoded }} {% endautoescape %} 
+8
source

You will probably find that with Django you can get quotes. I recently had a similar problem with the Jinja2 template. In my case, JSON was going into an HTML data attribute and avoiding things wrong. After I used the filter to be safe, it stopped avoiding quotes and there were inconsistent quotes. The decision was

 {% set dbl_quote='"' %} {{ encoded |replace(dbl_quote, '"') |safe}} 

but it will probably look different in Django.

You may need to use {% autoescape off %} or something similar instead if you produce templates directly in Javascript, etc.

+1
source

Source: https://habr.com/ru/post/1395630/


All Articles