如何在Django中去除文本输入中的HTML/JavaScript

95 投票
3 回答
40728 浏览
提问于 2025-04-15 11:40

从一个字符串中去掉所有的HTML和JavaScript,最简单的方法是什么?

3 个回答

1

Django 3

{{ the_value | striptags | safe | escape }}
54

这是一个关于 striptags 模板过滤器的内容。

{{ value|striptags }}
189

Django提供了一个工具函数,可以用来去掉HTML标签:

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

在旧版本的Django(1.7之前)中,这个函数使用起来不太安全,但现在使用它是完全安全的。这里有一篇文章,讨论了这个问题在当时的相关性。

撰写回答