2

I read this : https://stackoverflow.com/a/17090205/6426449

And I made a list that cannot be used on username in django.

list : FORBIDDEN_USERNAME_LIST = ['admin', 'master', 'owner']

So I made a code like this :

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

But It seems that it does not work.

Maybe I think, match = re.search("r'\b"+item+"\b'", username) Here is problem.

How can I fix that?

touchingtwist
  • 1,930
  • 4
  • 23
  • 38

3 Answers3

2

You could simply use 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.

Example in 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']
Roland Smith
  • 42,427
  • 3
  • 64
  • 94
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'})
Exprator
  • 26,992
  • 6
  • 47
  • 59
  • Thanks Exprator, but what if `username = admin123` ? I want to also ban all username with any of forbidden_username_list. – touchingtwist Dec 27 '17 at 09:49
1

Just use this statement:

match = re.search(r'[%s]+' % item, username, re.I)

instead of this:

match = re.search("r'\b"+item+"\b'", username)
Dmitry
  • 6,716
  • 14
  • 37
  • 39
Veera Balla Deva
  • 790
  • 6
  • 19