Django RegexValidator无法按预期工作 [英] Django RegexValidator Not working as expected
问题描述
我被RegexValidator类困住了。
I'm stuck with the RegexValidator Class.
我试图允许在Character字段中输入一些已定义的HTML(p,ul,li)标记。以下正则表达式完全满足我的需要,但我很难实现它。
I'm trying to allow input of some defined HTML(p, ul, li) tags in a Character Field. The following Regex does exactly what I need but I'm having difficulty implementing it.
<\/?(?!p|ul|li)[^/>]*>
我正尝试通过以下方式将其添加到Django模型中:
I'm trying to implment it into my Django model in the following way:
description = models.CharField(max_length = 255, validators=[
RegexValidator(
regex = r'<\/?(?!p|ul|li)[^/>]*>',
message = 'Disallowed Tags',
code = 'DISALLOWED_TAGS',
),
],
)
我正在使用Django 1.6。当我实现上述代码时,似乎所有表单提交(使用管理界面)都无法通过验证。
I'm using Django 1.6. When I implement the above code, it seems that all form submissions (Using Admin Interface) fail validation.
有什么想法吗?
谢谢
推荐答案
做自己的验证器,如果regexp匹配项抛出错误,因为它是不允许的。
此处有关验证器的更多信息。 p>
Do your own validator and if the regexp matches throw an error since it shouldn't be allowed.
here more info about validator.
import re
from django.core.exceptions import ValidationError
def test(val):
if re.match('<\/?(?!p|ul|li)[^/>]*>', val):
raise ValidationError('Disallowed Tags')
class Foo(models.Model):
name = models.CharField(max_length = 150, validators=[test])
这篇关于Django RegexValidator无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!