我嘗試導入from django.http import HttpResponse
,但我得到以下異常:進口的Django模塊
ImportError: Settings cannot be imported, because environment variable
DJANGO_SETTINGS_MODULE is undefined.
誰能幫幫我好嗎?
在此先感謝
我嘗試導入from django.http import HttpResponse
,但我得到以下異常:進口的Django模塊
ImportError: Settings cannot be imported, because environment variable
DJANGO_SETTINGS_MODULE is undefined.
誰能幫幫我好嗎?
在此先感謝
Django使用名爲DJANGO_SETTINGS_MODULE
找出其中的全局配置文件是一個環境變量。 DJANGO_SETTINGS_MODULE
必須引用包含您的配置設置的Python模塊,並且此模塊必須位於Python路徑中。如果你不想使用一個全局配置模塊無論出於何種原因,你必須使用一個使用設置任何的Django代碼之前調用從django.conf
settings.configure
:
from django.conf import settings
settings.configure(DEBUG=True, TEMPLATE_DEBUG=True,
TEMPLATE_DIRS=('/home/web-apps/myapp',
'/home/web-apps/base'))
的更多信息,可以找到in the Django docs。
如果你想從Python腳本中使用Django,你必須像上面說的那樣設置設置模塊。
做的另一種方式,是如下:
#!/usr/bin/python
from django.core.management import setup_environ
import os
import settings
os.environ['DJANGO_SETTINGS_MODULE'] = "mysite.settings" # or just "settings" if it's on the same directory as settings.py
from mysite.myapp.models import * # import models, etc, only *after* setting up the settings module
setup_environ(settings)
# insert your code here, say saving an entry
c = MyClass()
c.text = "Hello!"
c.save()