2013-04-13 51 views
7


我的目標是在Django創建一個自定義用戶模型1.5不能在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(「公司」)(蟒蛇manage.py createsuperuser) 我的問題:。
如何創建爲我的應用超級用戶沒有一家公司 我試圖使自定義MyUserManager沒有任何成功:

class MyUserManager(BaseUserManager): 
    ... 

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

或者我必須爲此用戶創建一家假公司嗎? 謝謝

+0

爲什麼需要企業自定義MyUserManager? – iMom0

+0

在我的模型中,沒有公司的用戶不能存在。但是超級用戶有一個例外。我在沒有REQUIRED_FIELDS的情況下收到了此錯誤:IntegrityError:app_myuser.company_id可能不是NULL –

+1

您可以爲所有人指定默認公司。 – iMom0

回答

3

有三種方式讓您在這種情況下

1)請有關業公司不需要company = models.ForeignKey('Company',null=True)

2)添加默認的公司,並提供爲默認值外鍵字段company = models.ForeignKey('Company',default=1)#其中1是創建公司的ID

3)保留模型代碼原樣。爲超級用戶添加假超級用戶,例如'Superusercompany' 將其設置爲create_superuser方法。

UPD:根據您的意見3將是最好的解決方案,不要打破你的灌木邏輯。

2

感謝這裏您的反饋是我所做的解決方案: ,我創建了一個默認的公司

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 
相關問題