Django supprimer superutilisateur

Cela peut être un doublon, mais je n'ai trouvé la question nulle part, alors je vais aller de l'avant et demander:

Existe-t-il un moyen simple de supprimer un superutilisateur du terminal, peut-être analogue à la commande createsuperuser de Django?

26
demandé sur Quentin Donnellan 2014-11-03 14:36:06

3 réponses

Il N'y a pas de commande intégrée mais vous pouvez facilement le faire à partir du shell:

> python manage.py shell
$ from django.contrib.auth.models import User
$ User.objects.get(username="joebloggs", is_superuser=True).delete()
42
répondu Timmy O'Mahony 2018-07-16 20:16:06

Voici une simple commande de gestion personnalisée, à ajouter à 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

0
répondu Ehvince 2018-04-18 13:41:14

une réponse pour les personnes qui n'ont pas utilisé le modèle utilisateur de Django a remplacé un modèle utilisateur personnalisé Django.

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

Maintenant pour supprimer un régime enregistré d' SUPERUSER dans notre système:

python3 manage.py shell

>>>(InteractiveConsole)
>>>from yourapp.models import TheUserProfile
>>>TheUserProfile.objects.all(email="The email you are looking for", is_superuser=True).delete()
0
répondu Braiden Gole 2018-09-10 00:38:26