python – 与django 1.7和自定义用户的AppRegistryNotReady错误

我正在创建一个自定义
django用户,并在尝试使用它时收到以下错误.我得到的错误如下

AppRegistryNotReady: Models aren't loaded yet.

我的模特

class MyCustomUserManager(BaseUserManager):

    def create_user(self, username, email, password=None, **kwargs):
        if not username:
            raise ValueError("Username must be defined for users")

        if not kwargs.get('email'):
            raise ValueError("Users must have a valid email")

        user = self.model(username=username, email=self.normalize_email(email), **kwargs)

        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, username, email, password, **kwargs):
        user = self.create_user(username, email,  password, **kwargs)
        user.is_admin = True
        user.save()


class MyCustomUser(AbstractBaseUser):
    username = models.CharField(max_length=40, unique=True)
    email = models.EmailField(max_length=255, unique=True, verbose_name=_('Email Address'))
    date_of_birth = models.DateField(auto_now=False, blank=False, null=False, verbose_name=_("Ημ. Γεννήσεως"))
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    first_name = models.CharField(max_length=40, blank=False, null=False, verbose_name=_("Όνομα"))
    last_name = models.CharField(max_length=40, blank=False, null=False, verbose_name=_("Επίθετο"))
    friends = models.ManyToManyField('self', related_name="friends")

    objects = MyCustomUserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email',]

    def get_full_name(self):
        return "%s %s" % (self.first_name, self.last_name)    

    def __unicode__(self):
        return self.get_full_name()

    class Meta:
        verbose_name = _('Χρήστης')
        verbose_name_plural = _('Χρήστες')

我还设置了设置文件以包含我的新自定义用户模型.

(在settings.py内)

AUTH_USER_MODEL = 'myapp.MyCustomUserModel'

登录shell时尝试使用我的新用户类型

from django.contrib.auth import get_user_model
user = get_user_model().objects.all()

我得到上面的错误. Django 1.7有什么问题吗?

P.S:我使用makemigrations并迁移来制作模型,我支持virtualenv.

最佳答案 从django 1.7开始,你不能在models.py文件中使用get_user_model,否则你会遇到这个问题.细节/原因可以在
referencing the user model中看到

要解决此问题,请在models.py文件中而不是使用get_user_model引用自定义用户模型,您需要从设置中导入名称.

from django.conf import settings

class MyModel(models.Model):
    ...
    user = models.ForeignKey(settings.AUTH_USER_MODEL)

当您解决问题时,它将修复您的应用程序以及您的shell.

点赞