How to reset user passwords in Django applications
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.
Create a new user using
pythonmanage.pycreatesuperuserChange 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()