Saturday, November 15, 2014

How to avoid "Models aren't loaded yet." error in Django 1.7

Today, I's trying to run a python script to manipulate my Django app's models and got this error:

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

The script used to work before I upgraded my Django project to version 1.7. I then go back to the Django1.7 documentations I found this instruction:

https://docs.djangoproject.com/en/dev/releases/1.7/#standalone-scripts

Standalone scripts

If you’re using Django in a plain Python script — rather than a management command — and you rely on theDJANGO_SETTINGS_MODULE environment variable, you must now explicitly initialize Django at the beginning of your script with:
>>> import django
>>> django.setup()
Otherwise, you will hit an AppRegistryNotReady exception.

So, I modified my script as following:

#! /usr/bin/env python

def setup_environment():
pathname = os.path.dirname(sys.argv[0])
sys.path.append(os.path.abspath(pathname))
sys.path.append(os.path.normpath(os.path.join(os.path.abspath(pathname), '../')))
os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'

setup_environment()

import django
django.setup()
...

It works!