The other day I've been confronted with a strange situation: I forgot the admin password for a django application. I was playing with installing my own pypi repository, I've configured and deployed a test application and, after a couple of weeks, I forgot the password. I tried several times bu I knew that I used something silly and... unfortunate. Even worse, the user name I thought I used was not the one I had set up for the test. Oops :)
After looking online for options I've found the following:
- Reinstall the app - This would be a pity because I already have some data loaded in
- Go to the DB and reset the password (would need to calculate a new hash = not nice)
- Use the command line
Using the command line would make sense in this case, so here are the steps I followed:
Log in on your server's shell (e.g. ssh). If you don't have a shell, then you're out of luck.
Activate the python environment you're using for your web app. It's likely that you use a virtualenv, so if you have bash:
Of course, replace
/_your_/_virtenv_/_path_/ with the actual location of your virtual environment.
If you don't use virtualenv, replicate the setup steps you are performing when launching the application (setting up the PATH, environment variables etc.)
This will give you access to all python libraries, including django.
Use the shell, Luke
Enter django shell:
cd /_your_/_app_/_path_/ python manage.py shell
/_your_/_app_/_path_/with the location where your application code is placed.
Now you should have a python shell prompt.
from django.contrib.auth.models import User
Get the users:
users = User.objects.all()
If you don't have too many users, you may want to list them:
Select the user desired:
user = users
The first user is usually the admin user.
Set the new password:
Log in in your app with the user name and the new password
Although it looks complicated, the python side is quite simple. We do the extra assignment (
user = users) because
User.objects.all() is a lazy operation and it returns in fact a queryset.