【问题标题】:Django Exception : AppRegistryNotReady("Models aren't loaded yet.")Django 异常:AppRegistryNotReady(“模型尚未加载。”)
【发布时间】:2016-12-05 21:38:10
【问题描述】:

我在 AppRegistryNotReady 异常中发现了很多内容,但没有一个看起来具有防御性。我只想要关于该主题的 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()

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

【问题讨论】:

  • 你试过from django.contrib.auth.models import User吗?

标签: python django


【解决方案1】:

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()是在第一次导入模块时执行的,此时应用注册表还没有完全初始化。如果您需要在models.py 文件中使用get_user_model(),您应该在函数或方法中调用它,而不是在模块级别:

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

【讨论】:

  • 是的。我最终将 get_user_model() 放入了一个函数中。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-30
  • 2015-05-09
  • 2020-08-11
  • 2021-02-09
  • 1970-01-01
  • 2016-03-11
相关资源
最近更新 更多