Django delete superuser

PythonDjango

Python Problem Overview


This may be a duplicate, but I couldn't find the question anywhere, so I'll go ahead and ask:

Is there a simple way to delete a superuser from the terminal, perhaps analogous to Django's createsuperuser command?

Python Solutions


Solution 1 - Python

There's no built in command but you can easily do this from the shell:

> python manage.py shell
$ from django.contrib.auth.models import User
$ User.objects.get(username="joebloggs", is_superuser=True).delete()

Solution 2 - Python

No need to delete superuser...just create another superuser... You can create another superuser with same name as the previous one. I have forgotten the password of the superuser so I create another superuser with the same name as previously.

Solution 3 - Python

An answer for people who did not use Django's User model instead substituted a Django custom user model.

class ManagerialUser(BaseUserManager):
    """ This is a manager to perform duties such as CRUD(Create, Read,
     Update, Delete) """

    def create_user(self, email, name, password=None):
         """ This creates a admin user object """

         if not email:
             raise ValueError("It is mandatory to require an email!")

         if not name:
             raise ValueError("Please provide a name:")

         email = self.normalize_email(email=email)
         user = self.model(email=email, name=name)

         """ This will allow us to store our password in our database
         as a hash """
         user.set_password(password)
         user.save(using=self._db)

         return user


    def create_superuser(self, email, name, password):
         """ This creates a superuser for our Django admin interface"""

         user = self.create_user(email, name, password)
         user.is_superuser = True
         user.is_staff = True
         user.save(using=self._db)

         return user


class TheUserProfile(AbstractBaseUser, PermissionsMixin):
    """ This represents a admin User in the system and gives specific permissions
 to this class. This class wont have staff permissions """

    # We do not want any email to be the same in the database.
    email = models.EmailField(max_length=255, unique=True)
    name = models.CharField(max_length=255)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'

    REQUIRED_FIELDS = ['name',]

    # CLASS POINTER FOR CLASS MANAGER
    objects = ManagerialUser()

    def get_full_name(self):
        """ This function returns a users full name """

        return self.name

    def get_short_name(self):
        """ This will return a short name or nickname of the admin user
        in the system. """

        return self.name

    def __str__(self):
        """ A dunder string method so we can see a email and or
        name in the database """

        return self.name + ' ' + self.email

Now to delete a registered SUPERUSER in our system:

python3 manage.py shell

>>>(InteractiveConsole)
>>>from yourapp.models import TheUserProfile
>>>TheUserProfile.objects.all(email="The email you are looking for", is_superuser=True).delete()

Solution 4 - Python

Here's a simple custom management command, to add in myapp/management/commands/deletesuperuser.py:

from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
from django.core.management.base import CommandError


class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('username', type=str)

    def handle(self, *args, **options):
        try:
            user = User.objects.get(username=options['username'], is_superuser=True)
        except User.DoesNotExist:
            raise CommandError("There is no superuser named {}".format(options['username']))

        self.stdout.write("-------------------")
        self.stdout.write("Deleting superuser {}".format(options.get('username')))
        user.delete()
        self.stdout.write("Done.")

https://docs.djangoproject.com/en/2.0/howto/custom-management-commands/#accepting-optional-arguments

Solution 5 - Python

In the case of a custom user model it would be:

python manage.py shell  
from django.contrib.auth import get_user_model
model = get_user_model()
model.objects.get(username="superjoe", is_superuser=True).delete()

Solution 6 - Python

A variation from @Timmy O'Mahony answer is to use the shell_plus (from django_extensions) to identify your User model automatically.

python manage.py shell_plus
User.objects.get(
    username="joebloggs",
    is_superuser=True
).delete()

If the user email is unique, you can delete the user by email too.

User.objects.get(
    email="[email protected]",
    is_superuser=True
).delete()

Solution 7 - Python

There is no way to delete it from the Terminal (unfortunately), but you can delete it directly. Just log into the admin page, click on the user you want to delete, scroll down to the bottom and press delete.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionQuentin DonnellanView Question on Stackoverflow
Solution 1 - PythonTimmy O'MahonyView Answer on Stackoverflow
Solution 2 - PythonShubham MahitkarView Answer on Stackoverflow
Solution 3 - Pythonuser9180455View Answer on Stackoverflow
Solution 4 - PythonEhvinceView Answer on Stackoverflow
Solution 5 - PythonlhoupertView Answer on Stackoverflow
Solution 6 - PythonclaudiusView Answer on Stackoverflow
Solution 7 - PythontheProCoderView Answer on Stackoverflow