繁体   English   中英

如何在Django / Python中使用正则表达式匹配“单词”

[英]How to match a 'word' using regex in django/python

我正在使用Django / Python,并且希望能够防止用户使用以下单词:“登录”和“注销”作为用户名。 我当前的解决方案是使用正则表达式来检查其输入是否包含禁止的单词(登录,注销)。 如果重要的话,我正在使用从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的方法正则表达式,除非我错过了一些东西,但找不到解决方案。 我也尝试过,但无济于事。 我知道可行的唯一选择是在视图中实施验证:

#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')

但这对我来说并不理想。

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

请参阅编写验证器

暂无
暂无

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

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