简体   繁体   English

在Django的RegexValidator中引用搜索组

[英]Referencing search groups in Django's RegexValidator

I have a regex validator which has a named search group. 我有一个具有命名搜索组的正则表达式验证器。 Something like this: 像这样:

from django.core.validators import RegexValidator
my_validator = RegexValidator(r'^[a-zA-Z0-9]*/(?P<pk>[0-9]*)$')

Now, I use this to check patterns. 现在,我用它来检查模式。 Something like this: 像这样:

search = my_validator('articles/421')
search.group('pk')

The last line returns an error: 最后一行返回错误:

AttributeError: 'NoneType' object has no attribute 'group'

Why is this? 为什么是这样? Is a RegexValidator different from normal regexes, in the sense that it does not have groups? RegexValidator没有普通的正则表达式,因为它没有组?

Django RegexValidator is a callable class for model field validation. Django RegexValidator是用于模型字段验证的可调用类。 It's used by model fields to validate the value. 模型字段使用它来验证值。 Field calls its validators and checks if there's no ValidationError raised 字段调用其验证器,并检查是否未引发ValidationError

It has regex property, which is normal regex covered with lazy function decorator. 它具有regex属性,这是用惰性函数装饰器覆盖的常规regex。 If you need only regex, just use standard python's re. 如果只需要正则表达式,则只需使用标准python的re。

You can pass a list of RegexValidator (or similar classes/callables) to models field property validators like so: 您可以将RegexValidator(或类似的类/可调用对象)列表传递给模型字段属性验证器,如下所示:

url_validator = RegexValidator(r'^[a-zA-Z0-9]*/(?P<pk>[0-9]*)$')
url = forms.CharField(validators=[url_validator])

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

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