【问题标题】:Can't create super user with custom user model in Django 1.5无法在 Django 1.5 中使用自定义用户模型创建超级用户
【发布时间】:2013-04-05 23:22:21
【问题描述】:


我的目标是在 Django 1.5 中创建自定义用户模型

# myapp.models.py 
from django.contrib.auth.models import AbstractBaseUser

class MyUser(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
        db_index=True,
    )
    first_name = models.CharField(max_length=30, blank=True)
    last_name = models.CharField(max_length=30, blank=True)
    company = models.ForeignKey('Company')
    ...

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['company']

由于公司字段 (models.ForeignKey('Company') (python manage.py createsuperuser)),我无法创建超级用户。 我的问题:
如何在没有公司的情况下为我的应用程序创建超级用户。 我尝试制作自定义 MyUserManager 没有任何成功:

class MyUserManager(BaseUserManager):
    ...

    def create_superuser(self, email, company=None, password):
        """
        Creates and saves a superuser with the given email and password.
        """
        user = self.create_user(
            email,
            password=password,
        )
        user.save(using=self._db)
        return user

或者我必须为这个用户创建一个假公司吗? 谢谢

【问题讨论】:

  • 为什么需要公司?
  • 在我的模型中,没有公司的用户不能存在。但是超级用户有一个例外。我在没有 REQUIRED_FIELDS 的情况下收到此错误:IntegrityError: app_myuser.company_id may not be NULL
  • 您可以为所有人指定一个默认公司。

标签: django django-models foreign-keys


【解决方案1】:

在这种情况下,您有三种方法

1) 与公司建立关系 不需要company = models.ForeignKey('Company', null=True)

2) 添加默认公司并将其作为默认值提供给外键字段company = models.ForeignKey('Company', default=1) #其中1是创建公司的id

3) 保持模型代码不变。为名为“Superusercompany”的超级用户添加假公司 在 create_superuser 方法中设置它。

UPD:根据您的评论方式#3 将是不破坏您的业务逻辑的最佳解决方案。

【讨论】:

    【解决方案2】:

    感谢您的反馈,这是我提出的解决方案: 我在其中创建了默认公司的自定义 MyUserManager

        def create_superuser(self, email, password, company=None):
            """
            Creates and saves a superuser with the given email and password.
            """
    
            if not company:
                company = Company(
                    name="...",
                    address="...",
                    code="...",
                    city="..."
                )
                company.save()
    
            user = self.create_user(
                email,
                password=password,
                company=company
            )
            user.is_admin = True
            user.save(using=self._db)
            return user
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-23
      • 1970-01-01
      • 2013-09-29
      • 2020-08-22
      • 1970-01-01
      • 2021-01-15
      • 1970-01-01
      • 2021-12-01
      相关资源
      最近更新 更多