Operate Django from directly executing python file over command line

Recently I came across a problem which took me some time to find out.

I want to write a script that can take arguments to add user to my Django app. This problem was encountered:

django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured.

When I added

os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'

to the file, this error happend:

django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

So in the end, I used this:

import sys, os
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
import django
django.setup()

sys is needed for my snippet. You may remove it if you want.

Leave a comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.