1

In PyCharm, I created a blank new Django app. Having created some models and issued manage.py makemigrations and manage.py migrate, I tried to write a standalone script that would populate the database with initial data. In its imports I wrote:

from MyApp.models import Model1, Model2, …

Sadly, running this script in PyCharm throws an exception: django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

I Googled this exception, and found an answer in SO https://stackoverflow.com/a/27455703/4385532 advising to put this in the top of my script:

import os

os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'

So I did. Sadly, this didn’t fix the issue. Now I am greeted with another exception: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.

What should I do?

Community
  • 1
  • 1
  • 1
    Did you also do this: `import django; django.setup()`? – mechanical_meat Mar 26 '17 at 22:03
  • Did you configure PyCharm project to be a Django one? There's a couple settings there that you need to set up. – Andrey Shipilov Mar 27 '17 at 03:27
  • 1
    Unless you are doing something very unusual, 'a script to populate the database with initial data' would be a perfect use case for either fixtures or a data migration, depending on whether the data can be loaded as is (ie from json) or requires some manipulation. Check out those options before you attempt anything more complicated. – ChidG Mar 27 '17 at 04:43
  • @bernie, Thanks! adding this line seems to have fixed the issue. –  Mar 27 '17 at 14:48
  • 1
    @ChidG Well I was importing data from `xls` files. The script took f#cking 10 hours to complete, while importing the same data from `xls` files to Python dicts takes seconds. The resulting `.sqlite3` file is `14.3 MB` large, for sake why does writing `14.3 MB` data to HDD take 10 hours? Thanks for pointing fixtures and data migrations to me, I'll definitely take a look at this if I ever have to re-import this data, perhaps – just perhaps – it will be faster. –  Mar 27 '17 at 14:52
  • You could use a data migration in that case. The performance issue may be something different and not something I can comment on without knowing a lot more. – ChidG Mar 28 '17 at 02:40

1 Answers1

0

Make sure you also do:

import django 
django.setup()

To load your models.

Documentation: https://docs.djangoproject.com/en/1.10/topics/settings/#calling-django-setup-is-required-for-standalone-django-usage

mechanical_meat
  • 163,903
  • 24
  • 228
  • 223