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
python manage.py createsuperuser
- 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
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
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
5. Save the user object
Final step to ensure your changes are saved.