Django AppsNotLoaded
Question: I'm trying to make a python script to put some things in my database;

    
    
    from django.conf import settings
    settings.configure()
    import django.db
    from models import Hero #Does not work..?
    heroes = [name for name in open('hero_names.txt').readlines()]
    
    
    names_in_db = [hero.hero_name for hero in Hero.objects.all()] #ALready existing heroes
    for heroname in heroes:
        if heroname not in names_in_db:
            h = Hero(hero_name=heroname, portraid_link='/static/heroes/'+heroname)
            h.save()
    

The import throws the following

    
    
    Traceback (most recent call last):
      File "heroes_to_db.py", line 4, in <module>
        from models import Hero
      File "C:\Users\toft_\Desktop\d2-patchnotes-master\dota2notes\patch\models.py", line 5, in <module>
        class Hero(models.Model):
      File "C:\Python27\lib\site-packages\django\db\models\base.py", line 105, in __new__
        app_config = apps.get_containing_app_config(module)
      File "C:\Python27\lib\site-packages\django\apps\registry.py", line 237, 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 know I can do `python manage.py --shell` and write the code for hand but to
be honest, I dont want to. What am I missing ?


Answer: Django must configure all installed applications before you can use any
models. To do this you must call `django.setup()`

    
    
    import django
    django.setup()
    

[From the
documentation:](https://docs.djangoproject.com/en/1.10/ref/applications/#how-
applications-are-loaded)

> This function is called automatically:
>
>   * When running an HTTP server via Django’s WSGI support.
>   * When invoking a management command.
>

>
> It must be called explicitly in other cases, for instance in plain Python
> scripts.

