我正在尝试创建一个存储主题标签的模型。
验证器似乎无法正常工作,使该字段接受所有输入,我无法找到解决方案。
这是我的模特:
class Hashtags(models.Model):
hashtag_validator = RegexValidator(r'^[#](\w+)$', "Hashtag doesn't comply.")
hashtag_id = models.AutoField(primary_key=True)
hashtag_text = models.CharField(max_length=100, validators=[hashtag_validator], unique=True)
def get_id(self):
return self.hashtag_id
def get_text(self):
return self.hashtag_text
答案 0 :(得分:3)
您可以将其更改为以下给定的代码,以使其正常工作
hashtag_validator = CharField(
max_length=50,
required=True, #if you want that field to be mandatory
validators=[
RegexValidator(
regex='^[#](\w+)$',
message='Hashtag doesnt comply',
),
]
)
希望有所帮助!!
如果这导致问题,您可以尝试编写自己的验证器
from django.core.exceptions import ValidationError
import re
def validate_hash(value):
reg = re.compile('^[#](\w+)$')
if !reg.match(value) :
raise ValidationError(u'%s hashtag doesnot comply' % value)
并将您的模型字段更改为
hashtag_validator = models.Charfield(validators=[validate_hash])
答案 1 :(得分:0)
除了S.Ali答案:
基于here
中的示例def uncvalidator(value):
"""Custom UNC path validator"""
import re
from django.utils.translation import gettext_lazy as _
UNC_REGEX = r'^local.company/some/share'
regex = re.compile(UNC_REGEX, re.IGNORECASE)
if not regex.match(value):
raise ValidationError(
_('Entered path %(value)s is incorrect.'),
params={'value': value},
)
unc = models.CharField(
validators=[uncvalidator],
)