Why does Django say I haven't set DATABASE_ENGINE yet?
I have a Django project, and I'm somewhat of a newbie in it. I have the following PyUnit test trying to save an object into a PostgreSQL database:
import unittest
from foo.models import ObjectType
class DbTest(unittest.TestCase):
def testDBConnection(self):
object_type = ObjectType()
object_type.name = 'Test Object'
object_type.description = 'For testing purposes'
object_type.save()
And my database settings are like this:
DATABASE_ENGINE = 'postgresql_psycopg2'
DATABASE_NAME = 'FOO'
DATABASE_USER = 'username'
DATABASE_PASSWORD = 'password'
DATABASE_HOST = 'localhost'
DATABASE_PORT = '5432'
I ran pyth开发者_如何学运维on manage.py syncdb for my project, which worked successfully, so my database should be setup properly. However I get the following error when I try to run the above unit test:
File "C:\Python26\lib\site-packages\django\db\backends\dummy\base.py", line 15, in complain raise ImproperlyConfigured, "You haven't set the DATABASE_ENGINE setting yet." ImproperlyConfigured: You haven't set the DATABASE_ENGINE setting yet.
Has anyone ever had experience with a problem like this? If so, any advice on where to start? Thanks!
That's probably because you're running tests directly, i.e. just python testfile.py
. This way you effectively bypass all Django mechanisms and use Model classes directly.
The downside is, the DB backend isn't set up automatically (by Django, which loads settings.py
and connects to the appropriate DB), hence the error you're experiencing.
I suppose there is a workaround around this problem, but it requires knowledge of internal Django workings for sure.
What you should do, instead, is launch your test via Django's testing framework (check out the documentation). It will take care of setting the DB connection properly, etc. There are also snazzy features like test fixtures.
Your Django settings file needs to have been loaded before you can import your models. If you can't use Django's testing framework, then perhaps you can use this code in your tests:
from django.conf import settings
settings.configure(
DATABASE_ENGINE='postgresql_psycopg2',
DATABASE_NAME='FOO',
DATABASE_USER='username',
DATABASE_PASSWORD='password',
DATABASE_HOST='localhost',
DATABASE_PORT='5432',
INSTALLED_APPS=('foo',)
)
or, if you don't need to be so explicit, then you can probably just do this:
import django.core.management
from foo import settings
django.core.management.setup_environ(settings)
You should be able to set the environment variable DJANGO_SETTINGS_MODULE=myapp.settings and have that work for standalone scripts.
in Linux/bash you'd do: export DJANGO_SETTINGS_MODULE=myapp.settings
精彩评论