如何在Django/python中使用regex匹配单词

2024-09-29 22:21:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是Django/Python,我希望能够阻止用户使用这些词:“login”和“logout”作为用户名。我目前的解决方案是使用正则表达式检查输入是否包含禁止使用的单词(login、logout)。如果重要的话,我使用的是从AbstractBaseUser扩展的自定义user_model。在

#models.py
username = models.CharField(max_length=14, blank=False, unique=True,
validators=[
validators.RegexValidator(
re.compile('^[^:;\'\"<>!@#$%|\^&\*\(\)~`,.?/=\-\+\\\{\}]? [\w]+$'),
#the line below is my regex for finding the words
re.compile(r'\blogout\b'))],

#variations i've tried are
#re.compile('\bword\b')
#re.compile(r'\b[^word]\b')
#re.compile(r'\Blogout\B')
#re.compile(r"\b(logout)\b")
#re.compile(r'(\bword\b)')
#re.compile('\blogout\b' or '\blogin\b')
#re.compile(r'\b'+'logout'+'\b')
#re.compile(r'^logout\w+$' or r'\blogin\b', re.I)
#re.match(r'\blogout\b','logout') 
#etc...
error_messages={'required':
                    'Please provide a username.',
                    'invalid': 'Alphanumeric characters only',
                    'unique': 'Username is already taken.'},
)

我已经读过:Python's how-to Regular Expressions除非我漏掉了什么,但我找不到解决办法。我也试过,但没用。我知道唯一可行的方法是在视图中实现验证:

^{pr2}$

但这对我来说并不理想。在


Tags: orthedjangoreismodelsusernamelogin
1条回答
网友
1楼 · 发布于 2024-09-29 22:21:03

您必须使它成为一个单独的验证器;您将第二个正则表达式作为消息传递到RegexValidator()对象中。在

只需使用一个简单的函数来验证值;这里不需要正则表达式,而是希望使值失效。编写一个只与负数匹配的正则表达式会变得很复杂,这不是您要在这里执行的操作:

from django.core.exceptions import ValidationError

forbidden = {'login', 'logout'}

def not_forbidden(value):
    if value in forbidden:
        raise ValidationError(u'%s is not permitted as a username' % value)


username = models.CharField(max_length=14, blank=False, unique=True, validators=[
        validators.RegexValidator(r'^[^:;\'\"<>!@#$%|\^&\*\(\)~`,.?/=\-\+\\\{\}]? [\w]+$'),
        not_forbidden,
    ])

Writing validators。在

相关问题 更多 >

    热门问题