Django异常:AppRegistryNotReady(“模型尚未加载。”)

时间:2016-12-05 21:38:10

标签: python django

我在AppRegistryNotReady Exception上发现了很多内容,但它们似乎都不具备防御性。我只想要关于这个主题的2美分信息。

我的django项目工作正常。我创建了一个新的应用程序,并创建了以下模型。没有观点,没有网址没有。只是一个模特。

from __future__ import unicode_literals

from django.db import models

# Create your models here.

from django.conf import settings
from django.core.exceptions import ValidationError
from django.contrib.auth import get_user_model
User = get_user_model()

class File(models.Model):
    path = models.TextField() #The path does not include MEDIA_ROOT, obviously
    filename = models.CharField(max_length=500)
    # file = models.FileField(upload_to=upload_to)
    file = models.FileField(upload_to=path+filename)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, models.PROTECT) #Protects User from being deleted when there are files left

    def clean(self):
        #Check if path has a trailing '/'
        if self.path[-1]!='/':
            self.path = self.path+"/"
        if self.filename[0]=='/':
            self.filename = self.filename[1:]

        #Get the full path
        username = self.user.__dict__[User.USERNAME_FIELD] #Need to do this the roundabout way to make sure that this works with CUSTOM USER MODELS. Else, we could have simply went for self.user.username
        self.path = "tau/"+username+"/"+self.path

    def save(self, *args, **kwargs):
        self.full_clean()
        return super(File, self).save(*args, **kwargs)

    def __str__(self):
        if path[-1]=='/':
            text = "\n"+str(path)+str(filename)
        else:
            text = "\n"+str(path)+"/"+str(filename)
        return text

然后我尝试在模型上制作颜色。并最终出现以下错误。

(test) ~/Workspace/WebDevelopment/Django/test/stud$python manage.py makemigrations
Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/home/raghuram/Workspace/WebDevelopment/Django/test/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "/home/raghuram/Workspace/WebDevelopment/Django/test/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 341, in execute
    django.setup()
  File "/home/raghuram/Workspace/WebDevelopment/Django/test/local/lib/python2.7/site-packages/django/__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/raghuram/Workspace/WebDevelopment/Django/test/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "/home/raghuram/Workspace/WebDevelopment/Django/test/local/lib/python2.7/site-packages/django/apps/config.py", line 199, in import_models
    self.models_module = import_module(models_module_name)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/home/raghuram/Workspace/WebDevelopment/Django/test/stud/tau/models.py", line 10, in <module>
    User = get_user_model()
  File "/home/raghuram/Workspace/WebDevelopment/Django/test/local/lib/python2.7/site-packages/django/contrib/auth/__init__.py", line 163, in get_user_model
    return django_apps.get_model(settings.AUTH_USER_MODEL)
  File "/home/raghuram/Workspace/WebDevelopment/Django/test/local/lib/python2.7/site-packages/django/apps/registry.py", line 192, in get_model
    self.check_models_ready()
  File "/home/raghuram/Workspace/WebDevelopment/Django/test/local/lib/python2.7/site-packages/django/apps/registry.py", line 131, in check_models_ready
    raise AppRegistryNotReady("Models aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.

为了完成测试,我将模型改为此,

class File(models.Model):
        file = models.FileField()

这阻止了例外。所以我的猜测就是异常被提升了。

from django.contrib.auth import get_user_model
User = get_user_model()

但我需要使用它,因为我正在使用自定义用户模型。关于如何实现它的任何想法?

1 个答案:

答案 0 :(得分:0)

AbstractBaseUser提供了get_username()方法,您可以使用它。它实际上和你正在做的一样:return getattr(self, self.USERNAME_FIELD)

class File(models.Model):
    ...
    def clean(self):
        #Check if path has a trailing '/'
        if self.path[-1]!='/':
            self.path = self.path+"/"
        if self.filename[0]=='/':
            self.filename = self.filename[1:]

        #Get the full path
        username = self.user.get_username()
        self.path = "tau/"+username+"/"+self.path

原始方法失败的原因是因为首次导入模块时执行get_user_model(),此时app注册表未完全初始化。如果您需要在get_user_model()文件中使用models.py,则应在函数或方法中调用它,而不是在模块级别调用它:

class File(models.Model):
    ...
    def clean(self):
        User = get_user_model()