Skip to content

Instantly share code, notes, and snippets.

@domodomodomo
Forked from jcinis/gist:2866253
Last active January 31, 2018 21:08
Show Gist options
  • Save domodomodomo/39e5ecf06e02d76ea2409e77db9d77cf to your computer and use it in GitHub Desktop.
Save domodomodomo/39e5ecf06e02d76ea2409e77db9d77cf to your computer and use it in GitHub Desktop.
Generate a random username for Django
"""Make a random username for Django, such as 'adf1-2dfa-dfc4-fa9a'."""
import random
import string
from django.contrib.auth import get_user_model
AuthUser = get_user_model()
def make_random_username(length=16,
allowed_chars=string.ascii_lowercase + string.digits,
slice_length=4, delimiter='-'):
while True:
random_string = get_random_string(length,
allowed_chars,
slice_length, delimiter)
try:
AuthUser.objects.get(username=random_string)
except AuthUser.DoesNotExist:
return random_string
def get_random_string(length=16,
allowed_chars=string.ascii_lowercase + string.digits,
slice_length=4, delimiter='-'):
random_string = ''.join([random.choice(allowed_chars)
for i in range(length)])
sliced_random_string_list = [random_string[i:i + slice_length]
for i in range(0, length, slice_length)]
sliced_random_string = delimiter.join(sliced_random_string_list)
return sliced_random_string
@domodomodomo
Copy link
Author

domodomodomo commented Jan 1, 2018

Supplement about function names.

  1. make_random_username
    This function's name is changed to make_random_username according to make_random_password
    Django Manual make_random_password http://bit.ly/2lrb0I9

  2. get_random_string
    According to crypto.py, this script also defines get_random_string.
    get_random_string function is defined in crpto.py below for making random password.
    GitHub django/django/utils/crypto.py http://bit.ly/2lxvdLR

AuthUser = get_user_model()

Instead of referring to User directly, you should reference
the user model using django.contrib.auth.get_user_model().
This method will return the currently active user model
– the custom user model if one is specified, or User otherwise.
get_user_model http://bit.ly/2zTZ71M

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment