If you've lost access to your Django superuser (admin) account, don't worry โ€” it's possible to reset the password using Django's shell and a few environment variables. This guide will walk you through the steps in a secure and straightforward way.

(Note: If you are still on development and you know the username of the django superuser go directly to step 3)


๐Ÿงฉ Step 1: Locate Your SECRET_KEY

First, you need to locate the SECRET_KEY used in your Django project. This is required because some parts of Django's user authentication depend on it.

Option A: SECRET_KEY is in settings.py

Open your projectโ€™s settings.py and check whether SECRET_KEY is defined directly inside the file:

SECRET_KEY = 'your_secret_key_here'

If it is, proceed to Step 2.

Option B: SECRET_KEY is stored externally

If the SECRET_KEY is not found directly in settings.py, it may be loaded from an environment variable or an external file. Here are ways to locate it:

  • Check Gunicorn Service (if you're using Gunicorn):
    cat /etc/systemd/system/gunicorn.service
  • Look for a .env File:

    Search your project or server for a .env file. This file often holds environment variables like the SECRET_KEY.

Set the SECRET_KEY in Your Terminal

Once you have the key, set it as an environment variable in your shell:

export SECRET_KEY='your_secret_key_in_plain_text'

โš ๏ธ This stores the key in plain text in your shell session. Be cautious.


๐Ÿ”Ž Step 2: Find the Superuser Username

If you already know the username of your Django superadmin, you can skip to Step 3. Otherwise, open the Django shell:

python manage.py shell

Then, run the following Python code:

from django.contrib.auth import get_user_model

User = get_user_model()
superadmins = User.objects.filter(is_superuser=True)

for user in superadmins:
    print(user.username)  # You can also print user.email or user.get_full_name()

This will list all superusers on your system.


๐Ÿ” Step 3: Change the Superuser Password

Now that you know the username, change the password using:

python manage.py changepassword <username>

You'll be prompted to enter the new password.


๐Ÿงน Step 4: Clear the Environment Variable

Even though the shell session will forget the variable when closed, it's good practice to clear it right away:

View the stored value:

echo $SECRET_KEY

Unset it:

unset SECRET_KEY

Confirm itโ€™s cleared:

echo $SECRET_KEY  # This should return nothing

โœ… Done!

Youโ€™ve successfully reset the password for your Django superadmin user. Always handle sensitive information like your SECRET_KEY with care, and follow secure coding and deployment practices.

If you found this helpful, feel free to share or bookmark for future reference!