eliott42
eliott42

Reputation: 41

Django - safely render HTML in template

I am building a django web application where the user can submit text via a tinymce editor.

For that task I use the django-tinymce extension.

The question:

Is it secure to render the HTML in the template using the safe filter like so ? :

{{ richtext | safe }}

If not, how can it be made safe ?

Upvotes: 4

Views: 2127

Answers (1)

xyres
xyres

Reputation: 21844

If the html is coming from a reliable source, such as yourself, then it's (most probably) safe. But if you're allowing your site's users to submit their own html markup, then it's not safe.

But sometimes it is necessary to display html markup in django's templates and there's no choice but to use the safe filter. In those cases, the solution is to "sanitize" the html code.

"Sanitizing" means you keep only the safe html tags in the data and remove all the unsafe or unwanted tags (like script or style tags).


For sanitizing the data, you can use the bleach library.

Here's an example (taken from docs):

import bleach

bleach.clean('an <script>evil()</script> example')

# Output -> u'an &lt;script&gt;evil()&lt;/script&gt; example'

There's also django app for this library: django-bleach.

Upvotes: 3

Related Questions