Django“NotperlyConfigured”,但并非总是

时间:2015-04-23 15:31:13

标签: python django

我正在使用Pycharm 4开始一个新的Django项目。我已经定义了各种模型,如果我运行测试,比如这个,

from django.test import TestCase
from models import OwnerDatabase

class TestZero(TestCase):
    def test_Settings(self):
        item=OwnerDatabase.objects.first
一切正常。但是在项目的不同部分,如果我有这个代码(一个独立的脚本)

from models import OwnerDatabase

该程序有以下追溯

  File "/home/piffy/PycharmProjects/Russeau/russeau/datasetcreate.py", line 9, in <module>
    from russeau.models import OwnerDatabase, PublishedDatabase
  File "/home/piffy/PycharmProjects/Russeau/russeau/models.py", line 4, in <module>
    class OwnerDatabase(models.Model):
  File "/home/piffy/PycharmProjects/Russeau/russeau/models.py", line 5, in OwnerDatabase
    time = models.DateTimeField()
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 1098, in __init__
    super(DateField, self).__init__(verbose_name, name, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 146, in __init__
    self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
  File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 46, in __getattr__
    self._setup(name)
  File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 40, in _setup
    % (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

但是,在manage.py中,我已经有了

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Russeau.settings")

虽然我对Django和Python比较陌生,但我的其他项目并没有这样的问题。关于如何继续,我也不知所措。

谢谢!

---更新:

感谢下面的Daniel,我添加了

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Russeau.settings")

所以错误现在改为

django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.

在良好的轨道上,但是......?

1 个答案:

答案 0 :(得分:2)

如果是独立脚本,则需要先设置Django设置。在这种情况下,manage.py与它无关,因为您没有使用它来调用您的脚本。要解决此问题,您有两种选择:

  1. 将此内容写在脚本的顶部:

    sys.path.append("/path/to/project") #Set it to the root of your project
    os.environ["DJANGO_SETTINGS_MODULE"] = "<project>.settings"
    django.setup()
    

    之后,您应该可以从项目中导入模型或任何需要的模型。如果需要,您可以查看this以获取更详细的说明。

  2. 创建custom management command,以便您可以致电python manage.py mycommand