我读到了这个:https://stackoverflow.com/a/17090205/6426449
我制作了一个不能在django用户名上使用的列表。
列表:FORBIDDEN_USERNAME_LIST = ['admin', 'master', 'owner']
所以我做了这样的代码:
views.py
def username_choice(request):
if request.method == "POST":
username = request.POST['username']
for item in forbidden.FORBIDDEN_USERNAME_LIST:
match = re.search("r'\b"+item+"\b'", username)
if match:
return JsonResponse({'result': item + 'banned username'})
但似乎它不起作用。
也许我想,match = re.search("r'\b"+item+"\b'", username)
这是问题。
我该如何解决?
答案 0 :(得分:2)
您可以简单地使用in
:
forbidden = ['admin', 'master', 'owner']
username = request.POST['username']
match = [nm for nm in forbidden if nm in username]
if match:
# part of the username is in the forbidden list.
IPython中的示例:
In [1]: forbidden = ['admin', 'master', 'owner']
In [2]: username = 'owner123'
In [3]: match = [nm for nm in forbidden if nm in username]
In [4]: match
Out[4]: ['owner']
答案 1 :(得分:1)
def username_choice(request):
if request.method == "POST":
username = request.POST['username']
for item in forbidden.FORBIDDEN_USERNAME_LIST:
if re.search(r'\b'+str(item)+'\\b', username, re.I):
return JsonResponse({'result': item + 'banned username'})
答案 2 :(得分:1)
只需使用此声明:
match = re.search(r'[%s]+' % item, username, re.I)
而不是:
match = re.search("r'\b"+item+"\b'", username)