简体   繁体   中英

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?

Django RegexValidator is a callable class for model field validation. It's used by model fields to validate the value. Field calls its validators and checks if there's no ValidationError raised

It has regex property, which is normal regex covered with lazy function decorator. If you need only regex, just use standard python's re.

You can pass a list of RegexValidator (or similar classes/callables) to models field property validators like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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