How to strip html/javascript from text input in django

PythonDjango

Python Problem Overview


What is the easiest way to strip all html/javascript from a string?

Python Solutions


Solution 1 - Python

Django provides an utility function to remove HTML tags:

from django.utils.html import strip_tags

my_string = '<div>Hello, world</div>'
my_string = strip_tags(my_string)
print(my_string)
# Result will be "Hello, world" without the <div> elements

This function used to be unsafe on older Django version (before 1.7) but nowadays it is completely safe to use it. Here is an article that reviewed this issue when it was relevant.

Solution 2 - Python

The striptags template filter.

{{ value|striptags }}

Solution 3 - Python

Django 3

{{ the_value | striptags | safe | escape }}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEldilaView Question on Stackoverflow
Solution 1 - PythonEldilaView Answer on Stackoverflow
Solution 2 - PythonAyman HouriehView Answer on Stackoverflow
Solution 3 - PythonAhmed ShehabView Answer on Stackoverflow