1

当我尝试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 的模型?

4

2 回答 2

0

您正在正确设置 sys.path,但是因为您正在处理 Django 模型,所以您还需要导入您的设置。

回溯应该给你一些关于哪里出了问题的迹象。特别是这一行:

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

查看此链接以了解正确导入 Django 模型的几种不同方法。

于 2013-04-03T13:53:34.677 回答
0
foo.bar.__path__.append('sample/foo/bar')
from foo.bar import app
于 2013-03-05T14:34:08.390 回答