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 the following command:
python manage.py shell
This will start an interactive Python shell with your Django project loaded.
- Reset the password In the shell, execute the following code:
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 use user.password = 'plain_text' as that would store the password unhashed.
- Exit the shell Once the password is updated, simply type:
exit()
or press Ctrl+D (on Unix-like systems) or Ctrl+Z then Enter (on Windows).
That’s it! 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 to the correct one
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 (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.
Top comments (0)