Reputation: 41
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
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 <script>evil()</script> example'
There's also django app for this library: django-bleach
.
Upvotes: 3