首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >运行初始生成时的Django 1.9 django.db.utils.OperationalError

运行初始生成时的Django 1.9 django.db.utils.OperationalError
EN

Stack Overflow用户
提问于 2016-03-14 07:26:25
回答 2查看 7.1K关注 0票数 0

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

我的models.py文件:

代码语言:javascript
复制
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文件:

代码语言:javascript
复制
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):“这是错误日志:

代码语言:javascript
复制
    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文件:

代码语言:javascript
复制
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'),
        }
    }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-03-14 10:09:36

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

您不能在导入项目时进行数据库查询,因为需要首先导入它,以便Django可以执行数据库迁移,只有这样,它才能创建执行查询所需的数据库表。

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

例如:

代码语言:javascript
复制
class ContactForm(forms.Form):
    dealer = forms.ModelChoiceField(
        queryset=Dealership.objects.all(),
        label="Service Center",
        required=True)

如果您希望自定义Dealership实例的显示方式,您将在医生们中找到说明。

票数 2
EN

Stack Overflow用户

发布于 2016-03-14 14:52:28

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

代码语言:javascript
复制
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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35981705

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档