How to reset Django superuser password

mahabub.devs3
Mahabubur Rahman
Published on Sep, 20 2024 1 min read 0 comments
image

If you forgot your django superuser password, there are some way to reset it. From them we will discus on python shell. If you forgot your username, then we will find back that as well.

 

Find  superuser's:

If you forgot superuser username then follow this. On your server terminal start python shell :

python manage.py shell

Now you can find out usernames are used for superuser with following command:

from django.contrib.auth import get_user_model
list(get_user_model().objects.filter(is_superuser=True).values_list('username', flat=True))

You will get result as bellow:

['rootuser', 'superuser']

If you get single result, you have single superuser and get multiple result if you have multiple superusers. Pick one that you want to change password.

Reset your superuser password

Open Django shell as above(python manage.py shell).Then write or copy/past this code:

 

from django.contrib.auth import get_user_model
def reset_password(u, password):
    try:
        user = get_user_model().objects.get(username=u)
    except:
        return "User could not be found"
    user.set_password(password)
    user.save()
    return "Password has been changed successfully"

 

It is the function we will use to change password for given username. Now you can simply change your password as bellow:

reset_password('username','password')
# for example: reset_password('rootuser','yoursecretpassowrd')

Using above command your superuser password changed successfully.

 

If you want to change password using email then change the following code:

user = get_user_model().objects.get(username=u)

To this:

user = get_user_model().objects.get(email=u)

 

If you still need help on resetting django admin password, please comment bellow.

 

0 Comments