How to strip html/javascript from text input in django

Question:

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

Asked By: Eldila

||

Answers:

The striptags template filter.

{{ value|striptags }}
Answered By: Ayman Hourieh

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.

Answered By: Eldila

Django 3

{{ the_value | striptags | safe | escape }}
Answered By: Ahmed Shehab
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.