[Django]-Why does Django say I haven't set DATABASE_ENGINE yet?

3👍

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.

2👍

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)
👤jps

2👍

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

👤sontek

Leave a comment