Django Password

Set Password Manually

It is easy to set password with the instance of User by set_password:

1
2
user = User.objects.create(username='my_username')
user.set_password('my_password')

But sometimes we want to bulk create users of we want to create an User model before saving into database. Your can create user model and set password manually.

1
2
3
4
5
6
7
from django.contrib.auth.hashers import make_password

user = User(
username='my_username',
password=make_password('my_password')
)
# now you get the instance of User model

How to Create an Raw Password Automatically?

Django provide a method make_random_password in the BaseUserManager. So you can generate a password like this.

1
2
3
from django.contrib.auth.models import User

User.objects.make_random_password() # not a good idea

But what if we just want to create a password without User involved? You can find the method make_random_password just call the function get_random_string defined in django.utils.crypto. So we make it easy like this.

1
2
3
4
5
from django.utils.crypto import get_random_string

raw_password = get_random_string() # try this one
raw_password = get_random_string(length=16)
raw_password = get_random_string(length=16, allowed_chars='abcdef0123456789')

Reference