Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jinja 2 - Django Form : rendering encodes HTML

I was testing Jinja2 in a Django project and have a strange output. When I render the form, some characters are HTML encoded (< > etc.)

In the template :

{{ form.as_p() }}

It renders to the browser :

<p><label for="id_username">Utilisateur:</label> <input autocomplete="off" id="id_username" type="text" name="username" maxlength="100" /></p> <p><label for="id_password">Mot de passe:</label> <input autocomplete="off" type="password" name="password" id="id_password" /></p>

Looking at sources :

&amp;lt;p&amp;gt;&amp;lt;label for=&amp;quot;id_username&amp;quot;&amp;gt;Utilisateur:&amp;lt;/label&amp;gt; &amp;lt;input autocomplete=&amp;quot;off&amp;quot; id=&amp;quot;id_username&amp;quot; type=&amp;quot;text&amp;quot; name=&amp;quot;username&amp;quot; maxlength=&amp;quot;100&amp;quot; /&amp;gt;&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;&amp;lt;label for=&amp;quot;id_password&amp;quot;&amp;gt;Mot de passe:&amp;lt;/label&amp;gt; &amp;lt;input autocomplete=&amp;quot;off&amp;quot; type=&amp;quot;password&amp;quot; name=&amp;quot;password&amp;quot; id=&amp;quot;id_password&amp;quot; /&amp;gt;&amp;lt;/p&amp;gt;

Does anyone know this problem ?

like image 239
Patrick Avatar asked Sep 14 '11 10:09

Patrick


People also ask

What is Jinja2 used for?

Jinja2 is a modern day templating language for Python developers. It was made after Django's template. It is used to create HTML, XML or other markup formats that are returned to the user via an HTTP request.

What is the Jinja2 delimiters for line statements in escaping from HTML?

The default Jinja delimiters are configured as follows: {% ... %} for Statements. {{ ... }} for Expressions to print to the template output. {# ... #} for Comments not included in the template output.

What is form AS_P in Django?

{{ form.as_p }} – Render Django Forms as paragraph. {{ form.as_ul }} – Render Django Forms as list.


1 Answers

Jinja2 tries to be safe by HTML-escaping the data. So you have to use |safe filter.

Though I haven't used Django with Jinja2, I believe this should work:

{{ form.as_p()|safe }}
like image 106
plaes Avatar answered Oct 09 '22 05:10

plaes