Django create new user with hashed password
In Django, you can create a new user with a hashed password using the create_user
method provided by the django.contrib.auth.models.User
model.
Here's an example:
from django.contrib.auth.models import User
# Create a new user with a hashed password
new_user = User.objects.create_user(
username='newuser',
email='[email protected]',
password='mysecretpassword'
)
In this example, we're creating a new User
object with the following attributes:
username
: the username for the new useremail
: the email address for the new userpassword
: the password for the new user, which will be hashed using themake_password
function
The create_user
method will automatically hash the password using the make_password
function, which is a part of the django.contrib.auth.hashers
module.
You can also specify additional attributes, such as first_name
and last_name
, when creating a new user:
new_user = User.objects.create_user(
username='newuser',
email='[email protected]',
password='mysecretpassword',
first_name='John',
last_name='Doe'
)
Note that the create_user
method will raise a ValidationError
if the password is too short or if the username is already taken.
Alternatively, you can use the create_superuser
method to create a superuser with a hashed password:
from django.contrib.auth.models import User
# Create a new superuser with a hashed password
new_superuser = User.objects.create_superuser(
username='superuser',
email='[email protected]',
password='mysecretpassword'
)
The create_superuser
method is similar to create_user
, but it sets the is_superuser
attribute to True
by default.