При переносе сайта на Django 1.9.0 + python 3.5.2 вылезла ошибка:
RuntimeError: Model class main.models.MyMain doesn't declare an explicit app_label and either isn't in an application in INSTALLED_APPS or else was imported before its application was loaded.(Этой ошибки нет на Django 1.9 + python 2.7 или Django 1.8 + python 3.5. На Django 1.10 + python 3.5 есть)
Причем вылезает она даже на максимально простом тестовом сайте, где вообще ничего нет, пара вьюх и ни одного модуля.
Полный лог ошибки:
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f48ef6c47b8>Мой код:
Traceback (most recent call last):
File “/home/maria/dj110/lib/python3.5/site-packages/django/utils/autoreload.py”, line 226, in wrapper
fn(*args, **kwargs)
File “/home/maria/dj110/lib/python3.5/site-packages/django/core/management/commands/runserver.py”, line 116, in inner_run
self.check(display_num_errors=True)
File “/home/maria/dj110/lib/python3.5/site-packages/django/core/management/base.py”, line 426, in check
include_deployment_checks=include_deployment_checks,
File “/home/maria/dj110/lib/python3.5/site-packages/django/core/checks/registry.py”, line 75, in run_checks
new_errors = check(app_configs=app_configs)
File “/home/maria/dj110/lib/python3.5/site-packages/django/core/checks/urls.py”, line 10, in check_url_config
return check_resolver(resolver)
File “/home/maria/dj110/lib/python3.5/site-packages/django/core/checks/urls.py”, line 19, in check_resolver
for pattern in resolver.url_patterns:
File “/home/maria/dj110/lib/python3.5/site-packages/django/utils/functional.py”, line 33, in __get__
res = instance.__dict__ = self.func(instance)
File “/home/maria/dj110/lib/python3.5/site-packages/django/core/urlresolvers.py”, line 417, in url_patterns
patterns = getattr(self.urlconf_module, “urlpatterns”, self.urlconf_module)
File “/home/maria/dj110/lib/python3.5/site-packages/django/utils/functional.py”, line 33, in __get__
res = instance.__dict__ = self.func(instance)
File “/home/maria/dj110/lib/python3.5/site-packages/django/core/urlresolvers.py”, line 410, in urlconf_module
return import_module(self.urlconf_name)
File “/home/maria/dj110/lib/python3.5/importlib/__init__.py”, line 126, in import_module
return _bootstrap._gcd_import(name, package, level)
File “<frozen importlib._bootstrap>”, line 986, in _gcd_import
File “<frozen importlib._bootstrap>”, line 969, in _find_and_load
File “<frozen importlib._bootstrap>”, line 958, in _find_and_load_unlocked
File “<frozen importlib._bootstrap>”, line 673, in _load_unlocked
File “<frozen importlib._bootstrap_external>”, line 665, in exec_module
File “<frozen importlib._bootstrap>”, line 222, in _call_with_frames_removed
File “/opt/work/darnius_svn/sites/mytest/mytest/urls.py”, line 2, in <module>
from main.views import main, edit, single
File “/opt/work/darnius_svn/sites/mytest/main/views.py”, line 5, in <module>
from .forms import MainForm
File “/opt/work/darnius_svn/sites/mytest/main/forms.py”, line 1, in <module>
from .models import MyMain
File “/opt/work/darnius_svn/sites/mytest/main/models.py”, line 7, in <module>
class MyMain(models.Model):
File “/home/maria/dj110/lib/python3.5/site-packages/django/db/models/base.py”, line 103, in __new__
“application was loaded. ” % (module, name))
RuntimeError: Model class main.models.MyMain doesn't declare an explicit app_label and either isn't in an application in INSTALLED_APPS or else was imported before its application was loaded.
./mytest/urls.py
from django.conf.urls import url from main.views import main, edit, single urlpatterns = [ # Examples: url(r'^$', main, name='main'), url(r'^edit/$', edit, name = 'edit'), url(r'^edit/(?P<pk>[0-9]*)/$', edit, name = 'edit'), url(r'^(?P<pk>[0-9]*)/$', single, name = 'single'), ]
# -*- coding:utf-8 -*- from django.utils.translation import ugettext_lazy as _ from django.shortcuts import render_to_response, redirect from .forms import MainForm from .models import MyMain def main(request): page_name = _(u"Заголовок главной страницы во вьюхе") return render_to_response('main.html', {'page_name': page_name}) def edit(request, pk=''): page_name = _(u"Заголовок страницы редактирования во вьюхе") if pk: m = MyMain.objects.get(id=pk) form = MainForm(instance=m) else: form = MainForm() if request.method == 'POST': if pk: form = MainForm(request.POST, instance=m) else: form = MainForm(request.POST) if form.is_valid(): form.save() return redirect('main') return render_to_response('edit.html', {'form':form, 'page_name': page_name}) def single(request, pk): page_name = _('Я простая одинокая запись, я никому не нужна') m = MyMain.objects.get(id=pk) return render_to_response('single.html', {'page_name': page_name, 'm': m})
from .models import MyMain from django.forms import ModelForm class MainForm(ModelForm): class Meta: model = MyMain
# -*- coding:utf-8 -*- from django.db import models from django.utils.translation import ugettext_lazy as _ # Create your models here. class MyMain(models.Model): title = models.CharField(max_length=200, verbose_name=_(u"Заголовок")) description = models.TextField(verbose_name=_(u"Описание")) price = models.FloatField(verbose_name=_(u"Цена"))
# -*- coding:utf-8 -*- # Django settings for mytest project.\ import os SECRET_KEY = 'abcdef' import django django.setup() DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'mytest', # Or path to database file if using sqlite3. # The following settings are not used with sqlite3: 'USER': 'qwerty', 'PASSWORD': '123456', 'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. 'PORT': '', # Set to empty string for default. } } # Hosts/domain names that are valid for this site; required if DEBUG is False # See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts ALLOWED_HOSTS = [] # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # In a Windows environment this must be set to your system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'ru' LANGUAGES = ( ('ru', 'Russian'), ('en', 'English'), ) PROJECT_ROOT = '/opt/work/darnius_svn/sites/mytest/' LOCALE_PATHS = ( os.path.join(PROJECT_ROOT, 'locale'), ) SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale. USE_L10N = True # If you set this to False, Django will not use timezone-aware datetimes. USE_TZ = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/var/www/example.com/media/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://example.com/media/", "http://media.example.com/" MEDIA_URL = '' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/var/www/example.com/static/" STATIC_ROOT = '' # URL prefix for static files. # Example: "http://example.com/static/", "http://static.example.com/" STATIC_URL = '/static/' # Additional locations of static files STATICFILES_DIRS = ( # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Make this unique, and don't share it with anybody. # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( #'django.middleware.common.CommonMiddleware', # Uncomment the next line for simple clickjacking protection: # 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'mytest.urls' # Python dotted path to the WSGI application used by Django's runserver. WSGI_APPLICATION = 'mytest.wsgi.application' TEMPLATE_DIRS = ( 'templates', # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) INSTALLED_APPS = ( 'main', ) PREFIX_DEFAULT_LOCALE = '' SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer' # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } }
Гугл предложил следующие варианты:
1) модель декларируется вне приложения (не мой случай)
2) Есть какой-то сигнал, который вызывается до загрузки модели (таковых нет)
3) Старые файлы .pyc вызывают ошибку (тоже не мой случай, удаление не помогло)
4) В корне проекта лежит лишний __init__.py (странная причина, но тоже не мой случай)
5) Неправильный порядок приложений в INSTALLED_APPS или приложение отсутствует в INSTALLED_APPS (в этом тестовом проекте приложение всего одно, оно есть в INSTALLED_APPS, так что тоже мимо)
Может, сталкивался кто с таким?