Django管理员:允许用户输入一些HTML [英] Django admin: allowing some HTML in user input
问题描述
默认情况下,Django管理员将从用户输入中删除所有HTML标签。我想允许一小部分标签,例如< a>
。最简单的方法是什么?我知道关于 allow_tags
,但它已被弃用。我还要小心手动将字符串标记为不安全的字符串。
By default, the Django admin strips away all HTML tags from user input. I'd like to allow a small subset of tags, say <a>
. What's the easiest way to do this? I know about allow_tags
, but it's deprecated. I also want to be careful about manually marking strings as safe that aren't.
推荐答案
如果外部库不是负担对于您,那么您必须尝试 django-bleach ,这将足以满足您的要求。它返回仅包含您指定的允许标签的有效HTML。
If external library isn't a burden for you, then you must try django-bleach, it will suffice your requirement. It returns valid HTML that only contains your specified allowed tags.
配置:$ settings $ <$ p
Configuration: in settings.py
BLEACH_ALLOWED_TAGS = ['p', 'b', 'i', 'u', 'em', 'strong', 'a']
BLEACH_ALLOWED_ATTRIBUTES = ['href', 'title', 'style']
BLEACH_STRIP_TAGS = True
用例:
1.在您的模型中:
Use cases: 1. In your models:
from django import models
from django_bleach.models import BleachField
class Post(models.Model):
title = models.CharField()
content = BleachField()
2。在您的表单中:
class PostForm(forms.ModelForm):
content = BleachField()
class Meta:
model = Post
fields = ['title', 'content']
-
在您的模板中:
In your templates:
{%load bleach_tags%}
{% load bleach_tags %}
{{unsafe_html | bleach}}
{{ unsafe_html|bleach }}
为了更多的使用,我建议你阅读文档。它很简单直接。
for more usage, I suggest you must read the documentation. Its quite easy and straight forward.
这篇关于Django管理员:允许用户输入一些HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!