1

在我的 django 项目中,我希望只有一个超级用户,并且不能通过python manage.py createsuperuser创建更多超级用户

可能吗?如果可能怎么办?

4

2 回答 2

1

您可以编写一个脚本来检查超级用户的数量。假设您想要 10 个超级用户,那么每次创建超级用户时都会计算其是否超过 10 个,并相应地给出错误/成功消息。

您可以按如下方式计算超级用户:

    from django.contrib.auth.models import User
    from django.http import HttpResponse

    user_obj = User.objects.all()
    c = 0
    for i in user_obj:
        if i.is_superuser():
            c += 1

    if c > 10:
        return HttpResponse('Cannot add anymore superusers')
    else:
        new_user  = User.objects.create_user(username = name, password = password)

当然,您必须制作一个表格来接受用户名和密码,但我已经给出了基本想法。
您还可以使用 python 的threading库来使事情异步

于 2016-03-27T09:13:00.043 回答
1

任何能够运行的人都python manage.py createsuperuser应该能够python manage.py dbshell在数据库中手动运行和创建超级用户。所以,无论如何,这应该是一个值得信赖的人。

如果只有受信任的人可以添加超级用户,那么只需告诉他们不要创建多个超级用户(尽管我想知道仅限于一个超级用户的目的是什么)。

但是,如果您想防止错误地创建多个超级用户python manage.py createsuperuser,您可以覆盖此命令

from django.contrib.auth.management.commands import createsuperuser
from django.core.management.base import CommandError

class Command(createsuperuser.Command):
    def handle(self, *args, **options):
        if self.UserModel.objects.filter(is_superuser=True).exists():
            raise CommandError("There is no room for two, go your way!")
        super().handle(*args, **options)

请注意,这不会阻止将用户设置为 django 管理界面的超级用户。

如果要彻底让创建两个超级用户成为不可能,可以直接在数据库级别添加约束。

另一种方法是子类化django.contrib.auth.models.User并定义:

SUPERUSER_ID = 1  # or whatever

@property
def is_superuser(self):
    return self.id == self.SUPERUSER_ID
于 2016-03-27T09:01:09.963 回答