django 脚本直接执行

node2:/zjzc/mysite#cat a1.py 
from polls.models import Question
for e in Question.objects.all():
  print e
node2:/zjzc/mysite#python a1.py
Traceback (most recent call last):
  File "a1.py", line 1, in <module>
    from polls.models import Question
  File "/zjzc/mysite/polls/models.py", line 7, in <module>
    class Reporter(models.Model):
  File "/zjzc/mysite/polls/models.py", line 8, in Reporter
    full_name = models.CharField(max_length=70)
  File "/usr/local/python27/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 1057, in __init__
    super(CharField, self).__init__(*args, **kwargs)
  File "/usr/local/python27/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 172, in __init__
    self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
  File "/usr/local/python27/lib/python2.7/site-packages/django/conf/__init__.py", line 56, in __getattr__
    self._setup(name)
  File "/usr/local/python27/lib/python2.7/site-packages/django/conf/__init__.py", line 39, in _setup
    % (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.




解决办法:
在import os之后添加
os.environ['DJANGO_SETTINGS_MODULE'] = 'myTest.settings'    # myTest是项目名称


node2:/zjzc/mysite#cat a1.py 
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
from polls.models import Question
for e in Question.objects.all():
  print e
node2:/zjzc/mysite#python a1.py
Traceback (most recent call last):
  File "a1.py", line 3, in <module>
    from polls.models import Question
  File "/zjzc/mysite/polls/models.py", line 7, in <module>
    class Reporter(models.Model):
  File "/usr/local/python27/lib/python2.7/site-packages/django/db/models/base.py", line 110, in __new__
    app_config = apps.get_containing_app_config(module)
  File "/usr/local/python27/lib/python2.7/site-packages/django/apps/registry.py", line 247, in get_containing_app_config
    self.check_apps_ready()
  File "/usr/local/python27/lib/python2.7/site-packages/django/apps/registry.py", line 125, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

node2:/zjzc/mysite#cat a1.py 
import os,django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
django.setup()
from polls.models import Question
for e in Question.objects.all():
  print e
node2:/zjzc/mysite#python a1.py
aaaaaaaaa
bbbbbbbbbbbbbb
c
ccccccccccc
what
why


原文地址:https://www.cnblogs.com/hzcya1995/p/13349266.html