运行初始makemigrations时Django 1.9 django.db.utils.OperationalError

时间:2016-03-14 07:26:26

标签: django django-models django-forms

在我运行" makemigrations new_project"之后,我第一次尝试在新创建的Django 1.9项目上进行迁移。迁移已创建,但是当我运行" migrate命令时,我得到一个django.db.utils.OperationalError,用于导入我在forms.py文件中创建的模型。

我的models.py文件:

from django.db import models
from django.conf import settings
from django.utils.translation import ugettext_lazy as _

class Dealership(models.Model):
country = models.ForeignKey(Country)

name = models.CharField(max_length=100)
address = models.CharField(max_length=255)
postal_address = models.CharField(max_length=255, null=True, blank=True)
gps_x = models.FloatField()
gps_y = models.FloatField()
slug = SlugField(max_length=255, original_field='name')

def __str__(self):
    return self.name

我的forms.py文件:

import re
from datetime import date, datetime

from django import forms
from django.conf import settings
from django.core.mail import EmailMessage
from django.core.validators import validate_email
from django.forms import extras
from django.utils.translation import ugettext_lazy as _

from new_project.models import Dealership

form ContactForm(forms.Form):

    DEALERSHIPS = []
    DEALERSHIPS.append(("", ("Select a dealer")))

    for dealer in Dealership.objects.all():
        DEALERSHIPS.append((dealer.name, _(dealer.name)))

    dealer = forms.ChoiceField(
        choices=DEALERSHIPS,
        label="Service Center",
        required=True)

....

错误抛出:" ContactForm(forms.Form):" 这是错误日志:

    Unhandled exception in thread started by <function wrapper at 0xb65e9064>
Traceback (most recent call last):
  File "/home/jcraine/Desktop/projects/new-project/env/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper
    fn(*args, **kwargs)
  File "/home/jcraine/Desktop/projects/new-project/env/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run
    self.check(display_num_errors=True)
  File "/home/jcraine/Desktop/projects/new-project/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 426, in check
    include_deployment_checks=include_deployment_checks,
  File "/home/jcraine/Desktop/projects/new-project/env/local/lib/python2.7/site-packages/django/core/checks/registry.py", line 75, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/home/jcraine/Desktop/projects/new-project/env/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 10, in check_url_config
    return check_resolver(resolver)
  File "/home/jcraine/Desktop/projects/new-project/env/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 19, in check_resolver
    for pattern in resolver.url_patterns:
  File "/home/jcraine/Desktop/projects/new-project/env/local/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/jcraine/Desktop/projects/new-project/env/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 417, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/home/jcraine/Desktop/projects/new-project/env/local/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/jcraine/Desktop/projects/new-project/env/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 410, in urlconf_module
    return import_module(self.urlconf_name)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/home/jcraine/Desktop/projects/new-project/src/new_project/urls.py", line 6, in <module>
    from new_project import views
  File "/home/jcraine/Desktop/projects/new-project/src/new_project/views.py", line 19, in <module>
    from new_project.forms import ContactForm, RequestTestDriveForm, \
  File "/home/jcraine/Desktop/projects/new-project/src/new_project/forms.py", line 72, in <module>
    class RequestTestDriveForm(forms.Form):
  File "/home/jcraine/Desktop/projects/new-project/src/new_project/forms.py", line 78, in RequestTestDriveForm
    for dealer in Dealership.objects.all():
  File "/home/jcraine/Desktop/projects/new-project/env/local/lib/python2.7/site-packages/django/db/models/query.py", line 258, in __iter__
    self._fetch_all()
  File "/home/jcraine/Desktop/projects/new-project/env/local/lib/python2.7/site-packages/django/db/models/query.py", line 1074, in _fetch_all
    self._result_cache = list(self.iterator())
  File "/home/jcraine/Desktop/projects/new-project/env/local/lib/python2.7/site-packages/django/db/models/query.py", line 52, in __iter__
    results = compiler.execute_sql()
  File "/home/jcraine/Desktop/projects/new-project/env/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 852, in execute_sql
    cursor.execute(sql, params)
  File "/home/jcraine/Desktop/projects/new-project/env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/home/jcraine/Desktop/projects/new-project/env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/home/jcraine/Desktop/projects/new-project/env/local/lib/python2.7/site-packages/django/db/utils.py", line 95, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/home/jcraine/Desktop/projects/new-project/env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/home/jcraine/Desktop/projects/new-project/env/local/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 323, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: new_project_dealership

有没有人知道如何解决这个问题?提前谢谢。

修改

这是我的settings.py文件:

import os

from django.contrib.messages import constants as message_constants
from django.utils.translation import ugettext_lazy as _

BASE_DIR = os.path.dirname(os.path.dirname(__file__))

SECRET_KEY = 'xy89(rhki@zxc7#)hsfauh!v1^9#^dxs8u@xt8_jo#wt)iqrn)'

DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []

INSTALLED_APPS = (
    'grappelli',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'new_project',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware'
)

ROOT_URLCONF = 'new_project.urls'

WSGI_APPLICATION = 'new_project.wsgi.application'

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

LANGUAGE_CODE = 'en-ZA'

LANGUAGE_COOKIE_AGE = None

LANGUAGE_COOKIE_NAME = 'django_language'

LANGUAGE_COOKIE_PATH = '/'

LOCALE_PATHS = (
    os.path.join(BASE_DIR, '..', 'locale'),
)

TIME_ZONE = 'Africa/Johannesburg'

USE_I18N = True

USE_L10N = False

USE_TZ = True

MEDIA_ROOT = os.path.join(BASE_DIR, '..', 'media') + os.sep

MEDIA_URL = '/media/'

STATIC_ROOT = ''

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, '..', 'static'),
)

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
)

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    'django.template.context_processors.media',
    "django.core.context_processors.static",
    "django.core.context_processors.tz",
    'django.core.context_processors.request',
    "django.contrib.messages.context_processors.messages"
)

TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, '..', 'templates'),
)

SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'

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,
        },
    }
}

DEBUG_TOOLBAR_CONFIG = {
    'INTERCEPT_REDIRECTS': False
}

INTERNAL_IPS = ('127.0.0.1', 'localhost')

MESSAGE_TAGS = {
    message_constants.DEBUG: 'alert',
    message_constants.INFO: 'alert alert-info',
    message_constants.SUCCESS: 'alert alert-success',
    message_constants.WARNING: 'alert alert-warning',
    message_constants.ERROR: 'alert alert-danger'
}

if DEBUG:  # Don't cache anything in debug
    CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
        }
    }
else:
    CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
            'LOCATION': os.path.join(BASE_DIR, 'cache'),
        }
    }

2 个答案:

答案 0 :(得分:2)

第78行的new_project/forms.py内部,您正在对表单模块的导入时间进行数据库查询。这不受支持,只有在应用程序完成初始化后才能进行任何数据库查询;通常,这意味着,在处理请求时。

在导入项目时无法进行数据库查询,因为需要首先导入它,以便Django可以执行数据库迁移,然后才能创建执行查询所需的数据库表。

更新:查看表单代码,您是否考虑使用ModelChoiceField而不是手动构建选项列表?

例如:

class ContactForm(forms.Form):
    dealer = forms.ModelChoiceField(
        queryset=Dealership.objects.all(),
        label="Service Center",
        required=True)

如果您想自定义Dealership的实例显示方式,您可以在the docs中找到相关说明。

答案 1 :(得分:0)

在加载python模块时执行ContactForm中的for循环,因此,在Django初始化之前执行它。相反,您可以在初始化时提供这些选择:

form ContactForm(forms.Form):

    def __init__(self, *args, **kwargs):
        super(ContactForm, self).__init__(*args, **kwargs)
         dealerships = []
         dealerships.append(("",("Select a dealer")))
         all_dealerships = Dealership.objects.all()
         for dealer in all_dealerships:
             dealerships.append((dealer.name, _(dealer.name)))

         self.fields['dealer'].choices = dealerships

    dealer = forms.ChoiceField(
        choices=[],
        label="Service Center",
        required=True)

但是,如文档所述:

  

请注意,选择可以是任何可迭代对象 - 不一定是列表或元组。这使您可以动态构造选择。 但是如果你发现你自己选择了动态的选择,你可能最好使用一个带有ForeignKey的正确数据库表。选择意味着静态数据不会发生太大变化,如果有的话

来源:https://docs.djangoproject.com/en/1.9/ref/models/fields/#field-choices