Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django: rendering a variable with safe filter without unicode 'u' type designator

I am trying to pass a dictionary to a django template. In the django view, the variable is initialized and passed as such:

foo = {'a':'b'}
...
return render(request, 'template.html', {'foo': str(foo)}

In the template, I have

{{ foo|default:"{}"|safe}}

In case it's relevant, I have the above line in a jquery snippet. That snippet is failing because the dict is being rendered as

[{'a': u'b'}] 

instead of what I expect:

[{'a': 'b'}] 

It seems the safe filter is not removing the unicode u preceding the dict value 'b'. How do I do that?

like image 496
Neil Avatar asked Mar 22 '13 12:03

Neil


People also ask

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

Can I use filter () in Django template?

Django Template Engine provides filters which are used to transform the values of variables;es and tag arguments. We have already discussed major Django Template Tags. Tags can't modify value of a variable whereas filters can be used for incrementing value of a variable or modifying it to one's own need.

What does safe filter do in Django?

This flag tells Django that if a “safe” string is passed into your filter, the result will still be “safe” and if a non-safe string is passed in, Django will automatically escape it, if necessary. You can think of this as meaning “this filter is safe – it doesn't introduce any possibility of unsafe HTML.”

What is Forloop counter in Django?

A for loop is used for iterating over a sequence, like looping over items in an array, a list, or a dictionary.


1 Answers

You should be using a function to explicitly convert it to JSON, because of a few subtle differences between JSON and the default Python stringification:

  • A string in JSON technically must be delimited with " rather than ', though parsers tend to accept the latter too (see the string rule on json.org)

  • Bool literals are lowercase

  • If your data contains things other than numbers, strings, lists and dicts, using str on them will probably silently produce invalid JSON

Use a template filter such as django-jsonify:

{% load jsonify %}
...
{{ foo|jsonify }}
like image 85
ebsddd Avatar answered Sep 22 '22 05:09

ebsddd