Python Django删除超级用户

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26713443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:54:29  来源:igfitidea点击:

Django delete superuser

pythondjango

提问by Quentin Donnellan

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 createsuperusercommand?

是否有一种简单的方法可以从终端中删除超级用户,可能类似于 Django 的createsuperuser命令?

采纳答案by Timmy O'Mahony

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

没有内置命令,但您可以从 shell 轻松执行此操作:

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

回答by Ehvince

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

这是一个简单的自定义管理命令,要添加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

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

回答by Braiden Gole

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

对于没有使用 Django 的用户模型的人的答案,而是替换了 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

Now to delete a registered SUPERUSERin our system:

现在删除SUPERUSER在我们系统中注册的:

python3 manage.py shell

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