簡體   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