当我尝试sys.path
从 django 项目中的文件添加新的 python 路径时出现错误。我这样做是因为我需要创建一个 python 脚本来在数据库中包含一个 csv 文件。我有一个像这样的一般项目的应用程序:
/project/Scripts/file.py
一般项目是这样的:
/project/project/
即,我需要在路径中包含它在一般项目中的应用程序,以使用此应用程序的模型。
我在文件中的行如下:
import sys
sys.path.append('absolut path')
from app import models
from app.models import model
当我从终端弹出这个文件时出现的错误是:
user:~/repositorios/project/Scripts$ python file.py
Traceback (most recent call last):
File "file.py", line 8, in <module>
from app import models
File "path", line 1, in <module>
from django.db import models
File "/usr/local/lib/python2.7/dist-packages/django/db/__init__.py", line 11, in <module>
if settings.DATABASES and DEFAULT_DB_ALIAS not in settings.DATABASES:
File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 52, in __getattr__
self._setup(name)
File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 45, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.user:~/repositorios/project/Scripts$ python file.py
Traceback (most recent call last):
File "file.py", line 8, in <module>
from app import models
File "path", line 1, in <module>
from django.db import models
File "/usr/local/lib/python2.7/dist-packages/django/db/__init__.py", line 11, in <module>
if settings.DATABASES and DEFAULT_DB_ALIAS not in settings.DATABASES:
File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 52, in __getattr__
self._setup(name)
File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 45, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
我有这样的项目结构:
- 页
- 脚本
- 文件.py
- 页
- 应用程序
- 初始化.py
- 模型.py
- 测试.py
- 视图.py
- 应用程序
- 脚本
我正在 Scripts 的“File.py”中编写代码,我想将“app”的模型使用到“Scripts”文件夹中。
当我尝试(在 File.py 中)
'导入应用程序'
'从应用程序导入模型'
出现一个错误,上面写着:“模块'app'不存在”。
我尝试使用(在 File.py 中)编写路径:
导入系统
sys.path.append(路径)
导入应用
从应用导入模型
如何在 File.py 中使用 app 的模型?