python - Django:在数据迁移中创建 super 用户

标签 python django django-models django-migrations django-managers

目标:自动创建 super 用户

我正在尝试在早期数据迁移中创建一个默认用户,特别是 super 用户,因此每当我的 Django 应用程序在 Docker 容器中运行时,它就已经有一个 super 用户,我可以用它访问管理站点。

我已经尝试了不同的选项来创建所述 super 用户,尽管我有一些功能选项(基于我的 docker-compose 文件的 command 参数),但我在添加初始数据时看到了对于 Django 项目,最佳实践是通过数据迁移来完成。

我的自定义用户

在我的 Django 项目中,我扩展了 AbstactBaseUser,以便我可以更改电子邮件字段的默认用户名字段要求。我的用户是这样的:

class UserManager(BaseUserManager):
    def create_user(self, email, password=None, **extra_fields):
        # Implementation...

    def create_superuser(self, email, password, **extra_fields):
        # Implementation...

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(
        verbose_name="email address",
        max_length=255,
        unique=True,
    )
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)

    objects = UserManager()

    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = []

    def __str__(self):
        return self.email

尝试失败

按照 Django 文档 here 进行操作我尝试使用以下代码在数据迁移中创建 super 用户,该代码位于我的应用程序的迁移文件夹中名为 0002_data_superuser 的文件中:

def generate_superuser(apps, schema_editor):
    User = apps.get_model("users.User")
    User.objects.create_superuser(
        email=settings.DJANGO_SUPERUSER_EMAIL,
        password=settings.DJANGO_SUPERUSER_PASSWORD,
    )

    print("\nInitial superuser created\n")

class Migration(migrations.Migration):

    dependencies = [
        ('users', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(generate_superuser)
    ]

但是,当运行我的 docker-compose 时,我遇到了这个错误:

AttributeError: 'Manager' object has no attribute 'create_superuser'

我尝试通过打印管理器进行调试,实际上,它没有必要的create_superuser。我的下一个想法是尝试重现 create_superuser 自己所做的事情,但我发现这是不可能的,因为我无法使用许多管理密码、散列、规范化电子邮件等的方法。

我从所有这些中了解到,问题在于管理器由于某种原因在迁移期间不可用,我想知道是否有解决方案。

最佳答案

手动复制create_user功能

进一步查看 Django 源代码,我发现有一种方法可以从 create_superuser 重现功能。通过从 django.contrib.auth.hashers 导入 BaseUserManager 和类方法 make_password,我想出了这个:

from django.contrib.auth.models import BaseUserManager
from django.contrib.auth.hashers import make_password

def generate_superuser(apps, schema_editor):
    User = apps.get_model("users.User")

    email = settings.DJANGO_SUPERUSER_EMAIL
    password = settings.DJANGO_SUPERUSER_PASSWORD

    user = User()
    user.email = BaseUserManager.normalize_email(email)
    user.password = make_password(password)
    user.is_staff = True
    user.is_superuser = True
    user.save()

可以达到目的。

不过,我不太喜欢它作为解决方案,因为它需要重新实现已经存在的 Django 方法,而该方法在程序的此时无法访问。

关于python - Django:在数据迁移中创建 super 用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72131424/

相关文章:

python - Django Rest-Framework 嵌套序列化器顺序

django - 对于我所有的外键,我应该在 Django 中使用 User 还是 UserProfile?

django - 使用来自另一个 QuerySet : Possible? 的查询过滤 django QuerySet

python - 如何在接收模型端明确显示 Django ManyToMany 关系

python - Django 有自动排序模型字段的方法吗?

python - 禁用 python 文件的 Apache 缓存

django - 我如何按 Django 中的计算字段复杂排序?

python - Django 外国模特

python - 安装 Pillow Raspbian Python 3.5 时出现问题(缺少 JPEG 依赖项)

python - 当新数据到来时,如何重新训练 pyspark 中保存的线性回归 ML 模型