Fix Django RuntimeError: Settings already configured when executed scripts manually


Sometimes we need to create independent files that need to load Django environment and to get executed manually outside from Django apps. For instance, we need to create backup.py which will backup the django project database but read settings.py for the database configuration.

Usually, we can do on this way, assume the files located in PROJECT/APPS/UTILS/backup.py

1
2
3
4
5
6
7
8
import os
import sys

# Load environment
CURRENT = os.path.abspath(os.path.dirname(__file__))
PROJECT = os.path.abspath(os.path.join(CURRENT, "..", ".."))

sys.path.insert(1, PROJECT)

Sometime this is works and sometime doesn’t like having error :

1
RuntimeError: Settings already configured.

To solve this problems, we need to change the way to load sys.path from “append” into “insert”. Because the problem was PROJECT is on last order in sys.path. Here is the solution

1
2
3
4
5
6
7
8
import os
import sys

# Load environment
CURRENT = os.path.abspath(os.path.dirname(__file__))
PROJECT = os.path.abspath(os.path.join(CURRENT, "..", ".."))

sys.path.insert(1, PROJECT)

Leave a Reply

Your email address will not be published. Required fields are marked *

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