I have a python script that runs on a cron job. The script uses the django ORM of a related web portal for db calls. However, I am having a tough time running the script from command line. At the top of the script I have:
import sys
sys.path.append('/Users/david542/Desktop/project/')
from project.home.models import Title, Order
And when I try running the script:
File "/Library/Python/2.7/site-packages/django/utils/functional.py", line 184, in inner
self._setup()
File "/Library/Python/2.7/site-packages/django/conf/__init__.py", line 40, in _setup
raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE)
ImportError: Settings cannot be imported, because environment variable
DJANGO_SETTINGS_MODULE is undefined
It seems I need to set the DJANGO_SETTINGS_MODULE path in my python script, but how exactly would I do this?
Assuming your project settings are in /Users/david542/Desktop/project/my_settings.py you need to set DJANGO_SETTINGS_MODULE to ‘my_settings’ to let Django know where it is.
To set the variable, just call your script using
Also, I would advise you not to hard-code the path to your project in your script but to pass it along using the PYTHONPATH environment variable, as follow:
Cheers,
Simon