简体   繁体   English

Django RegexValidator无法按预期工作

[英]Django RegexValidator Not working as expected

I'm stuck with the RegexValidator Class. 我陷入RegexValidator类。

I'm trying to allow input of some defined HTML(p, ul, li) tags in a Character Field. 我试图允许在“字符字段”中输入一些定义的HTML(p,ul,li)标签。 The following Regex does exactly what I need but I'm having difficulty implementing it. 下面的Regex完全可以满足我的需要,但是我很难实现它。

    <\/?(?!p|ul|li)[^/>]*>

I'm trying to implment it into my Django model in the following way: 我正尝试通过以下方式将其添加到我的Django模型中:

     description = models.CharField(max_length = 255, validators=[
                                        RegexValidator(
                                            regex =  r'<\/?(?!p|ul|li)[^/>]*>',
                                            message = 'Disallowed Tags',
                                            code = 'DISALLOWED_TAGS',
                                        ),
                                    ],
                               )

I'm using Django 1.6. 我正在使用Django 1.6。 When I implement the above code, it seems that all form submissions (Using Admin Interface) fail validation. 当我实现上述代码时,似乎所有表单提交(使用管理界面)都无法通过验证。

Any ideas? 有任何想法吗?

Thanks 谢谢

Do your own validator and if the regexp matches throw an error since it shouldn't be allowed. 做自己的验证器,如果regexp匹配项抛出错误,因为它是不允许的。
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]) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM