django.core.exceptions.ImproperlyConfigured:请求设置DEFAULT_INDEX_TAB LESPACE,但未配置设置

时间:2016-09-15 18:49:53

标签: python django

我正在使用Django 1.9.1和Python 3.5.2,我在运行使用Django模型的Python脚本时遇到问题。

C:\Users\admin\trailers>python load_from_api.py
Traceback (most recent call last):
  File "load_from_api.py", line 6, in <module>
    from movies.models import Movie
  File "C:\Users\admin\trailers\movies\models.py", line 5, in <module>
    class Genre(models.Model):
  File "C:\Users\admin\trailers\movies\models.py", line 6, in Genre
    id = models.CharField(max_length=10, primary_key=True)
  File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\db\models\fi
elds\__init__.py", line 1072, in __init__
    super(CharField, self).__init__(*args, **kwargs)
  File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\db\models\fi
elds\__init__.py", line 166, in __init__
    self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
  File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\conf\__init_
_.py", line 55, in __getattr__
    self._setup(name)
  File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\conf\__init_
_.py", line 41, in _setup
    % (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TAB
LESPACE, but settings are not configured. You must either define the environment
 variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing s
ettings.

这是脚本:

#!/usr/bin/env python
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "trailers.settings")
os.environ["DJANGO_SETTINGS_MODULE"] = "trailers.settings"
import django
django.setup()
import tmdbsimple as tmdb
from movies.models import Movie

#some code...

我无法弄清楚出了什么问题。任何帮助表示赞赏!

2 个答案:

答案 0 :(得分:2)

我想出了如何在不更改脚本的情况下运行它,而是使用

python manag.py shell

然后

exec(open('filename').read())

似乎工作正常。

答案 1 :(得分:0)

我建议使用Django Custom Management Commands - 它们非常易于使用,它们使用您的设置,您的环境,您可以传递参数,还可以编写帮助字符串,以便您可以使用--help

然后你只需用./manage.py my_custom_command

来调用它

或者,如果您只想运行脚本,请将其添加到您的脚本

project_path = '/home/to/your/trailers/project/src'
if project_path not in sys.path:
    sys.path.append(project_path)

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "trailers.common")

import django
django.setup()