django - 无法在 Django 1.5 中使用自定义用户模型创建 super 用户

标签 django django-models foreign-keys


我的目标是在 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),我无法创建 super 用户。 我的问题:
如何在没有公司的情况下为我的应用程序创建 super 用户。 我尝试制作自定义 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

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

最佳答案

在这种情况下,您可以采取三种方法

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

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

3) 保留模型代码不变。为 super 用户添加假公司,例如“Superusercompany” 在 create_superuser 方法中设置它。

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

关于django - 无法在 Django 1.5 中使用自定义用户模型创建 super 用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15988183/

相关文章:

django - 从 Django Oscar 中使用单元测试调用的 View 访问购物篮

django - 在模板中扩展ManyToManyField

ruby-on-rails - 您是否有任何原因不想在关联中使用foreign_key?

django - 从 coveralls.io 中删除测试?

python - 'BooleanField' 对象在 Django 中没有属性 'use_required_attribute'

python - 如何在 django 中使用嵌套查找?

python - 我无法解决 Django models.DateField ValidationError

python - 查询范围为2年的DateField

mysql - 我们可以将 M2M 关系的 PK 用于另一个 M2M 表吗?

mysql - #1215 - 无法添加外键约束 - 不是错误的数据类型