[Solved]-How do I execute an arbitrary script in the context of my Django project?

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 .

👤Udi

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()
👤caram

0👍

Best solution is provided in this article.

Hints: Make sure you are using correct path to settings module, in my case, I missed nested dirs named the same way. The best way to avoid my mistake is to use something like this template to start with.

Leave a comment