我的目标是在 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/