Scripts for a Django codebase

Author: Swen Kooij

Date: 2021-11-27

If you want to quickly use the Django ORM to query something or run some function in your codebase, you have three options:

A straight forward script that tries to import something from your Django codebase would quickly be met by the following error:

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

This error occurs because Django requires an initialization step where it loads the settings and runs the initialization for each registered Django app. We can initialize Django with two simple lines:

import os

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")

import django
django.setup()

# do anything

After django.setup() has been called, the app is fully initialized and you can safely import anything from your codebase without having a AppRegistryNotReady error thrown in your face.