0

我正在使用 Django/Python,我希望能够阻止用户使用这些词:“login”和“logout”作为他们的用户名。我目前的解决方案是使用正则表达式来检查他们的输入是否包含禁用词(登录、注销)。如果重要的话,我正在使用user_modelAbstractBaseUser.

#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 的操作方法正则表达式,除非我错过了一些东西,但我找不到解决方案。我也尝试过,但无济于事。我知道可行的唯一替代方法是在视图中实现验证:

#views.py
#login and logout are used by the system so are invalid for usernames
#updated
if clean['username'] == 'login' or 'logout':
   return HttpResponse('Invalid username')

但这对我来说并不理想。

4

1 回答 1

1

您必须将其设为单独的验证器;您将第二个正则表达式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,
    ])

请参阅编写验证器

于 2013-08-03T22:08:10.810 回答