DEV Community

Vincent Tommi
Vincent Tommi

Posted on

How to Reset a Django Admin Password Using the Django Shell

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

  1. Open the Django shell In your project directory (where manage.py is located), run the following command:
python manage.py shell
Enter fullscreen mode Exit fullscreen mode

This will start an interactive Python shell with your Django project loaded.

  1. 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()
Enter fullscreen mode Exit fullscreen mode

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.
  1. Exit the shell Once the password is updated, simply type:
exit()
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

Troubleshooting Tips

  1. “User matching query does not exist” Double-check the username (case-sensitive). You can list all users with:
User.objects.all()
Enter fullscreen mode Exit fullscreen mode
  1. 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')
Enter fullscreen mode Exit fullscreen mode

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)