web-dev-qa-db-ja.com

Django 1.8以降にデータを取り込む際の「モデルはまだロードされていません」エラー

私はこのコードを使用してデータベースにデータを入力しています:

import os
def populate():
    python_cat = add_cat('Python')

    add_page(cat=python_cat, 
    title="Official Python Tutorial",
    url="http://docs.python.org/2/tutorial/")

    add_page(cat=python_cat,
    title="How to Think like a Computer Scientist",
    url="http://www.greenteapress.com/thinkpython/")

    add_page(cat=python_cat,
    title="Learn Python in 10 minutes",
    url="http://www.korokithakis.net/tutorials/python/")

    Django_cat = add_cat(name="Django")

    add_page(cat=Django_cat,
    title="Official Django Tutorial",
    url="http://djangoproject.com/en/1.5/intro/tutorial01/")

    add_page(cat=Django_cat,
    title="Django Rocks",
    url="http://www.djangorocks.com/")

    add_page(cat=Django_cat,
    title="How to Tango with Django",
    url="htttp://www.tangowithdjango.com/")

    frame_cat = add_cat(name="Other Frameworks")

    add_page(cat=frame_cat, 
    title="Bottle",
    url="http://bottlepy.org/docs/dev/")

    add_page(cat=frame_cat, 
    title="Flask",
    url="http://flask.pocoo.org")

    # Print out what we have added to the user. 
    for c in Category.objects.all():
        for p in Page.objects.filter(category=c):
            print "- {0} - {1}".format(str(c), str(p))

def add_page(cat, title, url, views=0):
    p = Page.objects.get_or_create(category=cat, title=title, url=url, views=views)[0]
    return p

def add_cat(name):
    c = Category.objects.get_or_create(name=name)
    return c

if __== '__main__':
    print "Starting Rango population script..."
    os.environ.setdefault('Django_SETTINGS_MODULE', 'p.settings')
    from rango.models import Category, Page
    populate()

実行中

python c:\python27\p\populate_rango.py

エラーが発生します:

Staring Rango population script...
Traceback (most recent call last):
File "c:\python27\p\populate_rango.py", line 59, in <module>
populate()
File "c:\python27\p\populate_rango.py", line 4, in populate
python_cat = add_cat('Python')
File "c:\python27\p\populate_rango.py", line 52, in add_cat
c = Category.objects.get_or_create(name=name)
File "C:\Python27\Lib\site-packages\Django\db\models\manager.py", li
manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Python27\Lib\site-packages\Django\db\models\query.py", line
et_or_create
return self.get(**lookup), False
File "C:\Python27\Lib\site-packages\Django\db\models\query.py", line
clone = self.filter(*args, **kwargs)
File "C:\Python27\Lib\site-packages\Django\db\models\query.py", line
ilter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Python27\Lib\site-packages\Django\db\models\query.py", line
filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "C:\Python27\Lib\site-packages\Django\db\models\sql\query.py",
in add_q
clause, require_inner = self._add_q(where_part, self.used_aliases)
File "C:\Python27\Lib\site-packages\Django\db\models\sql\query.py",
in _add_q
current_negated=current_negated, connector=connector)
File "C:\Python27\Lib\site-packages\Django\db\models\sql\query.py",
in build_filter
lookups, parts, reffed_aggregate = self.solve_lookup_type(arg)
File "C:\Python27\Lib\site-packages\Django\db\models\sql\query.py",
in solve_lookup_type
_, field, _, lookup_parts = self.names_to_path(lookup_splitted, se
a())
File "C:\Python27\Lib\site-packages\Django\db\models\sql\query.py",
in names_to_path
field, model, direct, m2m = opts.get_field_by_name(name)
File "C:\Python27\Lib\site-packages\Django\db\models\options.py", li
get_field_by_name
cache = self.init_name_map()
File "C:\Python27\Lib\site-packages\Django\db\models\options.py", li
init_name_map
for f, model in self.get_all_related_m2m_objects_with_model():
File "C:\Python27\Lib\site-packages\Django\db\models\options.py", li
get_all_related_m2m_objects_with_model
cache = self._fill_related_many_to_many_cache()
File "C:\Python27\Lib\site-packages\Django\db\models\options.py", li
_fill_related_many_to_many_cache
for klass in self.apps.get_models():
File "C:\Python27\Lib\site-packages\Django\utils\lru_cache.py", line
rapper
result = user_function(*args, **kwds)
File "C:\Python27\Lib\site-packages\Django\apps\registry.py", line 1
_models
*self.check_models_ready()
File "C:\Python27\Lib\site-packages\Django\apps\registry.py", line 1
ck_models_ready
raise AppRegistryNotReady("Models aren't loaded yet.")
Django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.*

残りのファイルは問題ありませんが、このエラーが発生します。 Tango with Django bookのチュートリアルに従いますが、この本はDjango 1.5.4を参照しており、私はDjango 1.8、だから誰もここで私を助けることができますか?

36
Atul tyagi

Django 1.7rc2と同じ例外がありました。解決策は、プログラムの最初にこれらの行を追加することでした。

import Django
django.setup()

更新: これはDjango 1.8。

98
pdw

このエラーが発生していました。プロジェクトはDjango 1.4で始まり、1.5に進み、その後1.7になりました。wsgi.pyは次のようになりました。

import os
import sys

from Django.core.handlers.wsgi import WSGIHandler

os.environ['Django_SETTINGS_MODULE'] = 'myapp.settings'
application = WSGIHandler()

1.7スタイルのWSGIハンドラーに更新したとき:

import os
import sys

from Django.core.wsgi import get_wsgi_application

os.environ['Django_SETTINGS_MODULE'] = 'myapp.settings'
application = get_wsgi_application()

すべてが動作するようになりました。

4
Nick Spacek

Django 1.9.xの場合:

populate_rango.py:

import os
import sys

from Django.core.wsgi import get_wsgi_application

os.environ['Django_SETTINGS_MODULE'] = 'tango_with_Django_project.settings'
application = get_wsgi_application()

def populate():
    python_cat = add_cat('Python')

    add_page(cat=python_cat,
         title="Official Python Tutorial",
         url="http://docs.python.org/2/tutorial/")

    add_page(cat=python_cat,
        title="How to Think like a Computer Scientist",
        url="http://www.greenteapress.com/thinkpython/")

    add_page(cat=python_cat,
        title="Learn Python in 10 Minutes",
        url="http://www.korokithakis.net/tutorials/python/")

    Django_cat = add_cat("Django")

    add_page(cat=Django_cat,
        title="Official Django Tutorial",
        url="https://docs.djangoproject.com/en/1.5/intro/tutorial01/")

    add_page(cat=Django_cat,
        title="Django Rocks",
        url="http://www.djangorocks.com/")

    add_page(cat=Django_cat,
        title="How to Tango with Django",
        url="http://www.tangowithdjango.com/")

    frame_cat = add_cat("Other Frameworks")

    add_page(cat=frame_cat,
        title="Bottle",
        url="http://bottlepy.org/docs/dev/")

    add_page(cat=frame_cat,
        title="Flask",
        url="http://flask.pocoo.org")

    #Print out what we have added to the user.
    for c in Category.objects.all():
        for p in Page.objects.filter(category=c):
            print ("- {0} - {1}".format(str(c), str(p)))

def add_page(cat, title, url, views=0):
    p = Page.objects.get_or_create(category=cat, title=title, url=url, views=views)[0]
    return p

def add_cat(name):
    c = Category.objects.get_or_create(name=name)[0]
    return c

# Start execution here!
if __== '__main__':
    print ("Starting Rango population script...")
    os.environ.setdefault('Django_SETTINGS_MODULE', 'tango_with_Django_project.settings')
    from rango.models import Category, Page
    populate()
1
novice