about 8 years ago

I was given a task to randomly generate usernames and passwords for 80 users in Django. Here is how I did it:

Thanks to this excellent StackOverflow post, generating random characters become very easy:

import string
import random

def generate(size=5, numbers_only=False):
    base =  string.digits if numbers_only else string.ascii_lowercase + string.digits
    return ''.join(random.SystemRandom().choice(base) for _ in range(size))

I want to use lowercase characters for usernames and digits only for passwords. Thus, the optional parameter numbers_only is used to specific which format I want.

Then, open up the Django shell:

./manage.py shell

and Enter the following to the interactive shell to generate a user:

from django.contrib.auth.models import User
from note import utils

User.objects.create_user(utils.generate(), password=utils.generate(6, True))

I saved the generate() inside utils.py which is located inside a project named note. Modify from note import utils to suit your needs.

← Debug Gunicorn startup error JavaScript Closure →
comments powered by Disqus