Django AppsNotLoaded
<p>I'm trying to make a python script to put some things in my database;</p>

<pre><code>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()
</code></pre>

<p>The import throws the following</p>

<pre><code>Traceback (most recent call last):
  File "heroes_to_db.py", line 4, in &lt;module&gt;
    from models import Hero
  File "C:\Users\toft_\Desktop\d2-patchnotes-master\dota2notes\patch\models.py", line 5, in &lt;module&gt;
    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.
</code></pre>

<p>I know I can do <code>python manage.py --shell</code> and write the code for hand but to be honest, I dont want to. What am I missing ?</p>

<p>Django must configure all installed applications before you can use any models. To do this you must call <code>django.setup()</code></p>

<pre><code>import django
django.setup()
</code></pre>

<p><a href="https://docs.djangoproject.com/en/1.10/ref/applications/#how-applications-are-loaded" rel="nofollow">From the documentation:</a></p>

<blockquote>
  <p>This function is called automatically:</p>
  
  <ul>
  <li>When running an HTTP server via Djangoâs WSGI support.</li>
  <li>When invoking a management command.</li>
  </ul>
  
  <p>It must be called explicitly in other cases, for instance in plain Python scripts.</p>
</blockquote>

python django