3

При запуске сервера появляется ошибка:

(test_django) E:\test_django\courses_django>python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x039B6198>
Traceback (most recent call last):
  File "E:\test_django\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper
    fn(*args, **kwargs)
  File "E:\test_django\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run
    self.check_migrations()
  File "E:\test_django\lib\site-packages\django\core\management\base.py", line 442, in check_migrations
    executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
  File "E:\test_django\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__
    self.loader = MigrationLoader(self.connection)
  File "E:\test_django\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__
    self.build_graph()
  File "E:\test_django\lib\site-packages\django\db\migrations\loader.py", line 206, in build_graph
    self.load_disk()
  File "E:\test_django\lib\site-packages\django\db\migrations\loader.py", line 119, in load_disk
    "Migration %s in app %s has no Migration class" % (migration_name, app_config.label)
django.db.migrations.exceptions.BadMigrationError: Migration urls in app lesson_two has no Migration class

Файлы которые я редактировал: 1) В файле settings.py, в INSTALLED_APPS добавил 'lesson_two',. settings.py:

"""
Django settings for courses_django project.

Generated by 'django-admin startproject' using Django 2.1.3.

For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'p@8k2c(&6&2q-*ak+b6blic@$%%^%@-cckn^+(vp(sy9m60t@%'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'lesson_one',
    'lesson_two',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'courses_django.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'courses_django.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = '/static/'

2)couses_django/urls.py:

from django.conf.urls import url, include
from django.contrib import admin
from lesson_two import views

urlpatterns = [
    # url(r'', include('lesson_one.urls')),
    # path(r'^ admin/', admin.site.urls),
    # url(r'^', views.home),
    url(r'^', include('lesson_two.urls'))
]

3)views.py:

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
def home(request):
    return HttpResponse("Home page")

4)lesson_two\urls.py:

from django.conf.urls import url, include
from . import views

urlpatterns = [
    url(r'^$', views.home)
]

В чем может быть проблема?

1 ответ 1

2

Согласно ответу,

Исключение BadMigrationError: "Migration *** in app *** has no Migration class" выбрасывается, если папка migrations/содержит файл urls.py, который является не валидным миграционным файлом.


А судя по коду в django/db/migrations/loader.py:

if not hasattr(migration_module, "Migration"):
    raise BadMigrationError(
        "Migration %s in app %s has no Migration class" % (migration_name, app_config.label)
    )

Отсутствует класс Migration.

Ответ, с ошибкой по теме, и примером класса Migration


Документация по миграционным файлам (на русском): https://djbook.ru/rel1.8/topics/migrations.html#migration-files

1
  • спасибо вам большое. Проблема была в том, что папка migrations содержала в себе файл urls.py. После его удаления всё заработало. 9 ноя 2018 в 10:07

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.