1

I am new to django. Want to create tables in the Database of my project, so I searched the tutorial. models.py:

from django.db import models

class Blah(models.Model):
    first = models.IntegerField()
    second = models.IntegerField()

Script to write data into db:

from django.conf import settings

settings.configure()
from core.models import Blah
b = Blah(first = 1, second = 2) 
b.save()

When I am trying to launch the script with django 1.9, it gives me the error:

C:\Python27\Scripts\reports>to_db.py
Traceback (most recent call last):
  File "C:\Python27\Scripts\reports\to_db.py", line 4, in <module>
    from core.models import Blah
  File "C:\Python27\Scripts\reports\core\models.py", line 5, in <module>
    class Blah(models.Model):
  File "C:\Python27\lib\site-packages\django\db\models\base.py", line 94, in __new__
    app_config = apps.get_containing_app_config(module)
  File "C:\Python27\lib\site-packages\django\apps\registry.py", line 239, in get_containing_app_config
    self.check_apps_ready()
  File "C:\Python27\lib\site-packages\django\apps\registry.py", line 124, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

I have already added the app to INSTALLED_APPS and I am able to do the exact same commands with "manage.py shell", but not with the script.

What am I missing here?

Thanks

  • you are going to need to set the `DJANGO_SETTINGS` and `django.setup()` at a minimum ... what are you actually trying to do ... this is not typically how you would insert anything into your django db ... see https://docs.djangoproject.com/en/1.9/howto/initial-data/ as it seems very relevant to what I assume you are trying to do ... – Joran Beasley Feb 05 '16 at 01:23
  • If you do need to script against Django (and the ORM), you'll want to use the [shell admin command](https://docs.djangoproject.com/es/1.9/ref/django-admin/#shell), passing your script as input to it. [Related question](http://stackoverflow.com/questions/16853649/executing-python-script-from-django-shell) – Jake Kreider Feb 05 '16 at 02:25
  • Thank you very much for answers! Passing script as an argument works just fine for me. – Sergey Demchenko Feb 05 '16 at 02:36

1 Answers1

1

If you do need to script against Django (and the ORM), you'll want to use the shell admin command, passing your script as input to it. Related question

Community
  • 1
  • 1
Jake Kreider
  • 950
  • 7
  • 12