Well, I have a project structure like this one:
my_project
|-scripts
| |- my_script.py
|
|-django_project
|- myApp
| |- models.py
| |- ...
|- django_project
|- settings.py
|- ...
I run Django inside a virtualenv and in my_script.py
I have to use some of myApp.models
So, here is how I did:
my_script.py
:
#!/usr/bin/env python
import django
django.setup()
from myApp.models import foo
# do things
Since I am inside a virtualenv, to make django.setup()
work properly I set in my virtualenv ($VIRTUAL_ENV/bin/postactivate
):
export DJANGO_SETTINGS_MODULE = django_project.settings
and I added django_project
to the path:
$ workon my_virtualenv
$ python -c "import sys; print sys.path"
['', '/my_project/django_project', ...]
And that's all.
If I activate my virtualenv and then I run my_script.py
all works fine.
But If I schedule a similar cron
job:
00 00 * * * /.../.virtualenvs/my_virtualenv/bin/python /.../my_project/scripts/my_script.py >> /.../test/test.log 2>&1
I get this error:
django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
It seems like my_virtualenv
activation settings are not properly loaded.
Why does this happen, and how can I fix?