有時(shí)候我們希望在一個(gè)新的獨(dú)立腳本里面使用django的orm系統(tǒng)褂策。例如我曾在一個(gè)django項(xiàng)目里面,用tornado單獨(dú)實(shí)現(xiàn)了其中的IM(即時(shí)通信)功能完箩。如果直接import django的models的話乡括,會(huì)出現(xiàn)以下錯(cuò)誤
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.
顯然悲雳,這里的錯(cuò)誤信息提示我們django的配置有問(wèn)題,這意味著我們需要手動(dòng)在新的腳本里面指定django的設(shè)置文件————也就是setting.py文件缀程。做到這一步很簡(jiǎn)單搜吧,只需要在腳本的開(kāi)頭加上如下的代碼:
import sys
from django.core.wsgi import get_wsgi_application
sys.path.extend(['Path_to_your_django_project',])
os.environ.setdefault("DJANGO_SETTINGS_MODULE","Name_Of_Your_Django_Project.settings")
application = get_wsgi_application()
如此之后應(yīng)該就一切工作正常了。
The English version can be found on my personal blog: How to use django models out of django project