Django 1.5 で奇妙なエラーが発生しました: 以下のようなモデルを定義しました:
class Company(models.Model):
user = models.OnetoOneField(User)
agreed_to_terms = models.NullBooleanField(default=False)
address = models.CharField(_('Complete Address'),
max_length = 255, null = True, blank = True)
winning_bid = models.ForeignKey('Bid',
related_name='winning_bid',
blank = True, null = True)
bid_list = models.ManyToManyField('Bid',
related_name='bids',
blank = True, null = True)
...
class Bid(models.Model):
user = models.ForeignKey(User, null = True, blank = True)
description = models.TextField(_('Description'),
blank = True, null = True,)
volume = models.DecimalField(max_digits=7, decimal_places=3,
null=True, blank=True,)
...
# all other attributes are of the Boolean, CharField or DecimalField type. No Foreignkeys, nor ManytoManyFields.
Django 管理者を介してフォームに初期データを入力しようとすると、次のエラーが表示されます:
Exception Value:
"" needs to have value for field "company" before this many-to-many relationship can be used.
以下のトレースバックを参照してください。エラーメッセージは私にはあまり意味がありません。唯一の m2m 関係はbid_list
でありnull = True
、保存時に null でした。Django 1.5 には、変更ログを読んでいる間に発見できなかった新しいものがありますか (これは Django 1.5 での最初のプロジェクトです)。
興味深いことに、オブジェクトを に保存するとDjango shell
、エラー メッセージは表示されませんが、オブジェクトはエラー メッセージなしで保存されません。
In [1]: user = User.objects.get(username='admin')
In [2]: new_company = Company()
In [3]: new_company.user = user
In [4]: new_company.save() Out[4]: <Company: Company object>
In [5]: foo = Company.objects.all()
Out[5]: []
を使用して SQL ステートメントをトレースしようとすると、debug toolbar
SQL SELECT ステートメントのみが表示され、INSERT 要求は表示されません。
この奇妙な動作の説明は何ですか?
トレースバック:
Request Method: POST
Request URL: /admin/company/company/add/
Django Version: 1.5.1
Python Version: 2.7.1
Installed Applications:
('django.contrib.admin',
'django.contrib.admindocs',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.gis',
'django.contrib.humanize',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'crispy_forms',
'django_extensions',
'easy_thumbnails',
'registration',
'south',
'company',
'bid',
'debug_toolbar')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware')
Traceback:
File "/Users/neurix/Development/virtual/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/neurix/Development/virtual/lib/python2.7/site-packages/django/contrib/admin/options.py" in wrapper
372. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/Users/neurix/Development/virtual/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
91. response = view_func(request, *args, **kwargs)
File "/Users/neurix/Development/virtual/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
89. response = view_func(request, *args, **kwargs)
File "/Users/neurix/Development/virtual/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner
202. return view(request, *args, **kwargs)
File "/Users/neurix/Development/virtual/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper
25. return bound_func(*args, **kwargs)
File "/Users/neurix/Development/virtual/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
91. response = view_func(request, *args, **kwargs)
File "/Users/neurix/Development/virtual/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func
21. return func(self, *args2, **kwargs2)
File "/Users/neurix/Development/virtual/lib/python2.7/site-packages/django/db/transaction.py" in inner
223. return func(*args, **kwargs)
File "/Users/neurix/Development/virtual/lib/python2.7/site-packages/django/contrib/admin/options.py" in add_view
1008. self.save_related(request, form, formsets, False)
File "/Users/neurix/Development/virtual/lib/python2.7/site-packages/django/contrib/admin/options.py" in save_related
762. form.save_m2m()
File "/Users/neurix/Development/virtual/lib/python2.7/site-packages/django/forms/models.py" in save_m2m
84. f.save_form_data(instance, cleaned_data[f.name])
File "/Users/neurix/Development/virtual/lib/python2.7/site-packages/django/db/models/fields/related.py" in save_form_data
1336. setattr(instance, self.attname, data)
File "/Users/neurix/Development/virtual/lib/python2.7/site-packages/django/db/models/fields/related.py" in __set__
910. manager = self.__get__(instance)
File "/Users/neurix/Development/virtual/lib/python2.7/site-packages/django/db/models/fields/related.py" in __get__
897. through=self.field.rel.through,
File "/Users/neurix/Development/virtual/lib/python2.7/site-packages/django/db/models/fields/related.py" in __init__
586. (instance, source_field_name))
Exception Type: ValueError at /admin/company/company/add/
Exception Value: "<Company: Company object>" needs to have a value for field "company" before this many-to-many relationship can be used.
設定.py
import os, os.path, sys
DEBUG = True
TEMPLATE_DEBUG = DEBUG
# Setting up folders
abspath = lambda *p: os.path.abspath(os.path.join(*p))
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
TASK2_MODULE_PATH = abspath(PROJECT_ROOT, 'apps/')
sys.path.insert(0, TASK2_MODULE_PATH)
# Loading passwords
try:
from settings_pwd import *
except ImportError:
pass
AUTH_PROFILE_MODULE = 'profile.UserProfile'
#ALLOWED_HOSTS = [''] # not needed for DEBUG = True
TIME_ZONE = 'Europe/London'
LANGUAGE_CODE = 'en-uk'
LANGUAGES = [
("en", u"English"),
]
SITE_ID = 1
USE_I18N = True
USE_L10N = True
USE_TZ = True
if DEBUG:
MEDIA_ROOT = os.path.join(PROJECT_ROOT, "site_media", "media")
else:
MEDIA_ROOT = "folder_to_upload_files"
if DEBUG:
MEDIA_URL = "/media/"
else:
MEDIA_URL = "/media/uploads/"
if DEBUG:
STATIC_ROOT = os.path.join(PROJECT_ROOT, "site_media","static")
else:
STATIC_ROOT = "folder_to_static_files"
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(PROJECT_ROOT, "assets"),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
SECRET_KEY = '...'
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',)
ROOT_URLCONF = 'task2.urls'
WSGI_APPLICATION = 'task2.wsgi.application'
TEMPLATE_DIRS = (
os.path.join(PROJECT_ROOT, "templates"),
os.path.join(PROJECT_ROOT, "templates/pages"),)
INSTALLED_APPS = (
# Django apps
'django.contrib.admin',
'django.contrib.admindocs',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.gis',
'django.contrib.humanize',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
# third party apps
'crispy_forms',
'django_extensions',
'easy_thumbnails',
'registration',
'south',
# task2 apps
'profile',
'company',
)
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
)
log = DEBUG
if log:
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'simple': {
'format': '%(levelname)s %(message)s',
},
},
'handlers': {
'console':{
'level':'DEBUG',
'class':'logging.StreamHandler',
'formatter': 'simple'
},
},
'loggers': {
'django': {
'handlers': ['console'],
'level': 'DEBUG',
},
}
}
####################
# THIRD PARTY SETUPS
# For Crispy Forms
CRISPY_FAIL_SILENTLY = not DEBUG
CRISPY_TEMPLATE_PACK = 'bootstrap'
## For Django Registration
ACCOUNT_ACTIVATION_DAYS = 7
# for Django testing to avoid conflicts with South migrations
SOUTH_TESTS_MIGRATE = False
# Debug_toolbar settings
if DEBUG:
INTERNAL_IPS = ('127.0.0.1',)
MIDDLEWARE_CLASSES += (
'debug_toolbar.middleware.DebugToolbarMiddleware',
)
INSTALLED_APPS += (
'debug_toolbar',
)
DEBUG_TOOLBAR_PANELS = (
'debug_toolbar.panels.version.VersionDebugPanel',
'debug_toolbar.panels.timer.TimerDebugPanel',
'debug_toolbar.panels.settings_vars.SettingsVarsDebugPanel',
'debug_toolbar.panels.headers.HeaderDebugPanel',
#'debug_toolbar.panels.profiling.ProfilingDebugPanel',
'debug_toolbar.panels.request_vars.RequestVarsDebugPanel',
'debug_toolbar.panels.sql.SQLDebugPanel',
'debug_toolbar.panels.template.TemplateDebugPanel',
'debug_toolbar.panels.cache.CacheDebugPanel',
'debug_toolbar.panels.signals.SignalDebugPanel',
'debug_toolbar.panels.logger.LoggingPanel',
)
DEBUG_TOOLBAR_CONFIG = {
'INTERCEPT_REDIRECTS': False,
}
# Easy_Thumbnail setup
THUMBNAIL_ALIASES = {
'': {
'thumbnail': {'size': (50, 50), 'crop': True},
},
}