Farhan's Personal and Professional Blog

Custom Django Fixture Imports

I needed to convert an XML document into a customize Django model with modifications to the based on programmable logic. Converting it to my model’s fixture would take too long and be unnecessary work, so I instead opted to manually convert the data.

I figured I could just import the Django model object, as is follows:

from tester.models import Control
a = Control()

However, I got the following vexing error in red:

$ python
Traceback (most recent call last):
File "", line 1, in
from tester.models import Control
File "/home/nahraf/src/beater/tester/", line 5, in
class Control(models.Model):
File "/home/nahraf/src/beater/tester/", line 6, in Control
family = models.CharField(max_length=40)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/", line 1012, in __init__
super(CharField, self).__init__(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/", line 146, in __init__
self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
File "/usr/local/lib/python2.7/dist-packages/django/conf/", line 46, in __getattr__
File "/usr/local/lib/python2.7/dist-packages/django/conf/", line 40, in _setup
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

In short, the solution is to set your Django application’s settings prior to importing the Django object. (My “tester” application is called “beater” cuz I beat up on it 🙂

My corrected code is as follows:

import os
# This must be executed before the import below
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "beater.settings")
import django
from tester.models import Control

After that, the code was able to import and utilize object. I hope this helps!