如何从 django 中的文本输入中去除 html/javascript

从字符串中去除所有 html/javascript 的最简单方法是什么?

37772 次浏览

The striptags template filter.

\{\{ value|striptags }}

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.

Django 3

\{\{ the_value | striptags | safe | escape }}