Skip to main content

Command Palette

Search for a command to run...

How to reset user passwords in Django applications

Updated
2 min read
A

Software engineer since 2020. Previously an engineer in the aerospace industry.

I taught myself web development without going to bootcamp. I owe my career to developers who publish free tutorials.

I wanted to pass on the favour so in 2022, I created a website of beginner Django tutorials. It brings me joy to know that I've helped aspiring and junior developers learn Django faster.

Two years on, I've decided to say goodbye to Wordpress and hello to Hashnode.

What do you do when you can’t log into Django admin? If you’re developing locally, then you have a few options.

  1. Create a new user using python manage.py createsuperuser

  2. Change the password in the shell

You will be able to access most user data through the Django shell. The only thing you won’t be able to find are user’s passwords. This is because Django doesn’t store raw passwords in the database. However, you can still update the password using the set_password method.

Here’s what you need to do:

1. Open the Django shell

Make sure your virtual environment is active and your terminal is in the same directory as manage.py.

Type the following to open a session in the Django shell. This is like a python shell, except it has access to your project database.

python manage.py shell

2. Import the User model

>>> from django.contrib.auth import get_user_model
>>> User = get_user_model()

get_user_model is a useful utility to grab the user model, as it works regardless of whether you’re using the default User model or you have defined a custom model.

3. Get the user object

>>> user = User.objects.get(username="myuser")

Can’t remember your username? Query all of them.

>>> User.objects.all().values_list("username", flat=True)
<QuerySet ['user-a', 'user-b']>

4. Set the password

You might be tempted to try user.password = mynewpassword... but this will not work. You need to use the set_password method.

>>> user.set_password("my_new_password")

5. Save the user object

Final step to ensure your changes are saved.

>>> user.save()

More from this blog

C

CTRL+Z - a blog about Django

42 posts

A collection of articles to help developers get started with the Django web framework.