import django module
I am trying to import from django.http import HttpResponse
, but I am getting the following exception:
ImportError: Settings cannot be imported, because environment variable
DJANGO_SETTINGS_MODULE is undefined.
Could anyone help 开发者_运维知识库me please?
Thanks in advance
If you want to use Django from a (say) Python script, you have to setup the settings module as you said.
Another way of doing, is as follow:
#!/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()
Django uses an environment variable named DJANGO_SETTINGS_MODULE
to figure out where the global configuration file is. DJANGO_SETTINGS_MODULE
must refer to a Python module that contains your configuration settings, and this module must be on the Python path. If you don't want to use a global configuration module for whatever reason, you have to call settings.configure
from django.conf
before using any Django code that uses settings:
from django.conf import settings
settings.configure(DEBUG=True, TEMPLATE_DEBUG=True,
TEMPLATE_DIRS=('/home/web-apps/myapp',
'/home/web-apps/base'))
More information is to be found in the Django docs.
精彩评论