我在我的Django管理站点中使用TinyMCE。我需要验证没有不允许的HTML标记被提交。这就是我试过的:
1)验证方法
def check_for_invalid_html_tags(value) :
compiled_regex = re.compile('<(?!/?(p|div|ul|li)(>|\s))[^<]+?>')
if compiled_regex.match(value):
raise ValidationError('Invalid Tags')2)验证规则
content = tinymce_models.HTMLField(validators=[check_for_invalid_html_tags])这似乎不起作用,因为任何提交都是有效的。当我将tinymce_models.HTMLField更改为models.TextField时,规则工作得很好。因此,我认为这个问题是TinyMCE的结果。
有人能帮忙吗?
发布于 2014-06-25 20:49:12
我读了文档,match和search之间有一个细微的区别
比赛:
如果字符串开头有零个或多个字符.
搜寻:
扫描字符串寻找第一个位置..。
由于您要查找的内容可能在字符串中无处不在,所以您需要使用search而不是match。另外一点,您可能需要设置fagre.s或re.DOTALL,因为您的输入中可能有换行符。
做“.”特殊字符匹配任何字符,包括换行符;没有此标志,“。将匹配除了换行符以外的任何东西。
这是函子和工作解中的check_for_invalid_html_tags。
import re
class CheckForInvalidHtmlTags(object):
compiled_regex = re.compile('<(?!/?(p|div|ul|li)(>|\s))[^<]+?>')
def __call__(self, value):
if self.compiled_regex.search(value):
print 'error'
else:
print 'ok'
c = CheckForInvalidHtmlTags()
c('test test <a>test<a> test') # print error
c('test <p> test</p>') # print ok
c('test<a> test</a><p>test</p>test') # print error发布于 2014-06-24 18:32:46
您的验证方法实际上必须是一个验证器,它具有像__call__这样的特殊方法。使用django的核心验证器之一,比如regex验证器。
from django.core.validators import RegexValidator
check_for_invalid_html_tags = RegexValidator(
regex=''<(?!/?(p|div|ul|li)(>|\s))[^<]+?>'',
message='Invalid Tags',
code='invalid_content'
)然后在你的模型中:
content = tinymce_models.HTMLField(validators=[check_for_invalid_html_tags])https://stackoverflow.com/questions/24355811
复制相似问题