sys.path
djangoプロジェクトのファイルからPythonの新しいパスを追加しようとするとエラーが発生します。データベースにcsvファイルを含めるためにPythonのスクリプトを作成する必要があるため、これを行っています。私はこのような一般的なプロジェクトからのアプリを持っています:
/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.
私はこのようなプロジェクト構造を持っています:
- ページ
- スクリプト
- File.py
- ページ
- アプリ
- init .py
- models.py
- tests.py
- views.py
- アプリ
- スクリプト
Scriptsの「File.py」にコードを書いています。「app」のモデルを「Scripts」フォルダーに使用したいと思います。
(File.pyで)試してみると
「アプリのインポート」
「アプリのインポートモデルから」
「モジュール'アプリ'が存在しません」というエラーが表示されます。
(File.pyに)パスを書いてみます:
sysをインポート
sys.path.append(path)
アプリをインポート
アプリのインポートモデルから
File.pyでアプリのモデルを使用するにはどうすればよいですか?