Change a django password manually
2 min read

Change a django password manually

Change a django password manually

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:

  1. Log in on your server's shell (e.g. ssh). If you don't have a shell, then you're out of luck.

    ssh [email protected]
  2. Activate the python environment you're using for your web app. It's likely that you use a virtualenv, so if you have bash:

    source /_your_/_virtenv_/_path_/bin/activate

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

  1. Enter django shell:

    cd /_your_/_app_/_path_/
    python shell

    Change /_your_/_app_/_path_/ with the location where your application code is placed.

    Now you should have a python shell prompt.

  2. Import the User model:

    from django.contrib.auth.models import User
  3. Get the users:

    users = User.objects.all()

    If you don't have too many users, you may want to list them:

    print users
  4. Select the user desired:

    user = users[0]

    The first user is usually the admin user.

  5. Set the new password:


    and save
  6. 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[0]) because User.objects.all() is a lazy operation and it returns in fact a queryset.