Eldila
Eldila

Reputation: 15726

How to strip html/javascript from text input in django

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

Upvotes: 96

Views: 42187

Answers (3)

Ahmed Shehab
Ahmed Shehab

Reputation: 1867

Django 3

{{ the_value | striptags | safe | escape }}

Upvotes: 1

Eldila
Eldila

Reputation: 15726

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.

Upvotes: 190

Ayman Hourieh
Ayman Hourieh

Reputation: 137156

The striptags template filter.

{{ value|striptags }}

Upvotes: 54

Related Questions