How to prevent Django from autoescaping html

Question:

I entered a responsibility.description via the Django Admin panel that contained an embedded <a>. When showing it in the template I want the <a> to appear as a link instead of being escaped as &lt;a&rt;.

I found this advice (How to disable autoescape in django feeds?) but still doesn’t seem to work for me.

I’ve tried marking it as safe:

{% for responsibility in software.responsibilities.all %}
    <li>{{ responsibility.description|safe }}</li>
{% endfor %}

and also turning autoescape off:

{% for responsibility in software.responsibilities.all %}
    {% autoescape off %}
        <li>{{ responsibility.description }}</li>
    {% endautoescape %}
{% endfor %}

Am I missing something or are there any other methods I can try?

Here is the data that is stored in the database:

>>> Responsibility.objects.filter(id=38)
<QuerySet [<Responsibility: Created and ran test suites using a proprietary testing framework for “Stubbs the Zombie” (<a target="_blank" href="http://www.imdb.com/title/tt0498128/fullcredits?ref_=tt_cl_sm#cast">credited</a>), a game for Windows, Mac, and X-Box written in C/C++ utilizing the Halo game engine.>]>

and here is how it appears in the html:

<li>Created and ran test suites using a proprietary testing framework for "Stubbs the Zombie" (&lt;a target="_blank" href="http://www.imdb.com/title/tt0498128/fullcredits?ref_=tt_cl_sm#cast"&gt;credited&lt;/a&gt;), a game for Windows, Mac, and X-Box written in C/C++ utilizing the Halo game engine.</li>
Asked By: Nick Weseman

||

Answers:

You can use the html’s module, unescape method witch:

Convert all named and numeric character references (e.g. >, >,
&x3e;) in the string s to the corresponding unicode characters.

You can use it in one or both of the following ways:

  1. When you receive data to be stored in the database (POST, PUT etc.):

    from html import unescape
    
    to_be_stored = unescape(input_data)
    

    Then store to_be_stored in your database

  2. When you send data from the database to the template (GET, LIST etc.):

    from html import unescape
    
    class MyView():
        ...
        def get(self):
            ...
            responsibility = Responsibility.objects.filter(id=your_id)
            response['responsibility'] = unescape(responsibility.description)
            ...
    

    Then return/render/etc the response.

Answered By: John Moutafis

Do try |safe|escape

{% for responsibility in software.responsibilities.all %}
    <li>{{ responsibility.description|safe|escape }}</li>
{% endfor %}

Ref: safe

Answered By: parmer_110
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.