Django删除超级用户

时间:2014-11-03 11:36:06

标签: python django

这可能是重复的,但我无法在任何地方找到问题,所以我会继续问:

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

7 个答案:

答案 0 :(得分:55)

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

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

答案 1 :(得分:3)

无需删除超级用户...只需创建另一个超级用户...即可创建另一个具有与上一个相同名称的超级用户。 我忘记了超级用户的密码,所以我创建了另一个与以前同名的超级用户。

答案 2 :(得分:0)

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

答案 3 :(得分:0)

未使用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

现在要删除我们系统中已注册的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()

答案 4 :(得分:0)

没有办法从终端中删除它(不幸的是),但你可以直接删除它。只需登录管理页面,点击您要删除的用户,向下滚动到底部,然后按删除。

答案 5 :(得分:0)

在自定义用户模型的情况下:

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()

答案 6 :(得分:0)

@Timmy O'Mahony 答案的一个变体是使用 shell_plus(来自 django_extensions)来自动识别您的用户模型。

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

如果用户邮箱是唯一的,您也可以通过邮箱删除用户。

User.objects.get(
    email="joebloggs@email.com",
    is_superuser=True).delete()
)