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 code.py Traceback (most recent call last): File "code.py", line 1, in from tester.models import Control File "/home/nahraf/src/beater/tester/models.py", line 5, in class Control(models.Model): File "/home/nahraf/src/beater/tester/models.py", line 6, in Control family = models.CharField(max_length=40) File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 1012, in __init__ super(CharField, self).__init__(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 146, in __init__ self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 46, in __getattr__ self._setup(name) File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 40, in _setup % (desc, ENVIRONMENT_VARIABLE)) 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 django.setup() from tester.models import Control Control()
After that, the code was able to import and utilize object. I hope this helps!