How to Reset a Django Admin Password Using the Django Shell
Source: Dev.to
Forgetting the password for your Django admin account can be frustrating, but resetting it is quick and straightforward using the Django shell. This method works even if you no longer have access to the admin interface and doesn’t require any additional packages.
Step‑By‑Step Guide
Open the Django shell
In your project directory (where manage.py is located), run:
python manage.py shell
This starts an interactive Python shell with your Django project loaded.
Reset the password
In the shell, execute:
from django.contrib.auth.models import User
# Replace 'admin' with the actual username of the admin account
user = User.objects.get(username='admin')
# Set the new password (replace 'new_secure_password' with your desired password)
user.set_password('new_secure_password')
# Save the changes
user.save()
Important notes
- Use the correct username (it’s usually
admin, but it could be something else if you created a custom superuser). set_password()automatically hashes the password for you—never assignuser.password = 'plain_text'as that would store the password unhashed.
Exit the shell
After updating the password, type:
exit()
or press Ctrl+D (Unix‑like systems) or Ctrl+Z then Enter (Windows).
You can now log in to the Django admin interface (/admin/) using the username and the new password you just set.
Bonus: Resetting Password for Any User (Not Just Admin)
The same method works for any user in your database—just change the username:
user = User.objects.get(username='john_doe')
user.set_password('another_secure_password')
user.save()
Troubleshooting Tips
“User matching query does not exist”
Double‑check the username (it is case‑sensitive). You can list all users with:
User.objects.all()
Using a custom User model
If your project uses a custom user model (e.g., CustomUser), replace User with your model:
from myapp.models import CustomUser
user = CustomUser.objects.get(username='admin')
Conclusion
With just a few lines of code, you can regain access to your Django admin account in seconds. This technique is especially useful on production servers or when email‑based password resets are not configured.