gpt4 book ai didi

python - Django "ImproperlyConfigured",但并非总是如此

转载 作者:行者123 更新时间:2023-12-01 04:44:19 25 4
gpt4 key购买 nike

我正在使用 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 比较陌生,但我的其他项目没有这样的问题。我也很茫然,不知道该如何继续下去。

谢谢!

---更新:

感谢丹尼尔,我在下面添加了

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

所以错误现在改为

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

一切进展顺利,但是..?

最佳答案

如果是独立脚本,则需要先设置 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

关于python - Django "ImproperlyConfigured",但并非总是如此,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29828019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com