10


私の目標は、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']

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

または、このユーザーのために偽の会社を作成する必要がありますか? ありがとうございました

4

2 に答える 2

5

あなたのフィードバックのおかげで、私が作成したソリューションは次のとおりです。デフォルトの会社を作成したカスタム 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
于 2013-04-14T16:20:44.160 に答える