我的django网站非常实用,它与数据库和Web客户端进行通信。我的文件夹设置如下:
top
+--- django
+---my_framework
+--- models.py
+--- settings.py
+---lib
+--- scripts
+---scripts_that_do_stuff_from_console
+--- service_that_needs_access_to_models
我已经能够从我脚本文件夹中的不同scrips访问lib文件夹中的库,如下所示:
lib_path = os.path.abspath(os.path.join(os.path.join('..', 'django'),"lib"))
sys.path.append(lib_path)
这似乎不太优雅,但它确实有效。
我需要另一个在后台运行的应用程序,该应用程序与数据库通信并支持django框架并与控制台交互。 我想在models.py中访问一些模型,所以我尝试了这个:
lib_path = os.path.abspath(os.path.join(os.path.join('..', 'django'),"lib"))
sys.path.append(lib_path)
from models import SystemConfiguration
我收到此错误:
Traceback (most recent call last):
File "./imageHandler.py", line 14, in <module>
from models import SystemConfiguration
File "/home/jordan/django/my_framework/models.py", line 2, in <module>
from django.contrib.auth.hashers import make_password
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/__init__.py", line 7, in <module>
from django.middleware.csrf import rotate_token
File "/usr/local/lib/python2.7/dist-packages/django/middleware/csrf.py", line 14, in <module>
from django.utils.cache import patch_vary_headers
File "/usr/local/lib/python2.7/dist-packages/django/utils/cache.py", line 26, in <module>
from django.core.cache import caches
File "/usr/local/lib/python2.7/dist-packages/django/core/cache/__init__.py", line 34, in <module>
if DEFAULT_CACHE_ALIAS not in settings.CACHES:
File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 48, in __getattr__
self._setup(name)
File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 42, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting CACHES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
我知道脚本需要读取settings.py,所以我尝试了:
import settings as mySettings
settings.configure(default_settings=mySettings, DEBUG=True)
这并没有真正帮助。我已经戳了一段时间,但还没有取得任何进展。任何建议都是最受欢迎的。
更好地到达......我添加了这个(如Semprini建议的那样):
lib_path = os.path.abspath("/mnt/garageMonitor/django/lib")
sys.path.append(lib_path)
lib_path = os.path.abspath("/mnt/garageMonitor/django/garageMonitor")
sys.path.append(lib_path)
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from models import SystemConfiguration
现在我收到了这个错误:
django.core.exceptions.ImproperlyConfigured: Unable to detect the app label for model "MyClass." Ensure that its module, "models", is located inside an installed app.
MyClass位于models.py文件中,因此现在正确打开它,但还有其他错误......
答案 0 :(得分:1)
设置模块需要在开始时添加到os.environ dict中(可能在导入任何模型之前但在执行sys.path.append之后)
os.environ ['DJANGO_SETTINGS_MODULE'] ='设置'
文件夹布局:
Wibble Project>
manage.py
wibble>
settings.py #must contain 'stuff' as an app
stuff>
models.py
test.py
示例test.py:
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'wibble.settings'
from stuff.models import MyObject
print(MyObject.objects.all())
输出:
python test.py
[<MyObject: Object1>,<MyObject: Object2>]