无法在Django 1.5中使用自定义用户模型创建超级用户

时间:2013-04-13 13:13:36

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

或者我是否必须为此用户创建虚假公司? 谢谢

2 个答案:

答案 0 :(得分:5)

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

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

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

3)保持型号代码不变。为超级用户添加假comapny,例如'Superusercompany' 在create_superuser方法中设置它。

UPD:根据你的评论,3将是不打破你的灌木逻辑的最佳解决方案。

答案 1 :(得分:3)

感谢您的反馈,我的解决方案是: 我创建默认公司的自定义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
相关问题