9👍
The best way to execute a script with the correct django context is to set the DJANGO_SETTINGS_MODULE
environment variable to your settings module (and appropriate PYTHONPATH
if needed). In windows this usually means executing:
set DJANGO_SETTINGS_MODULE=setting
and in bash :
export DJANGO_SETTINGS_MODULE=setting
You can now import your models etc.
see: https://docs.djangoproject.com/en/dev/topics/settings/#designating-the-settings .
Note that in order to import the settings
module, one should use from django.conf import settings
. This takes into account the DJANGO_SETTINGS_MODULE
instead of automatically using settings.py .
2👍
Here’s the simplest solution:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
import django
django.setup()
Be sure to include this at the top of your python file, before importing any of your models.
Alternatively, you could use the solution pointed out by @beyondfloatingpoint:
import os, sys
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
sys.path.append("mysite")
os.chdir("mysite")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
0👍