2013-04-22 46 views
3

我遇到的Django 1.5奇怪的錯誤之前: 我已經定義了類似下面的模型:Django的:對象需要有字段中的值「......」這麼多的一對多關係可以用來

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管理的初始數據以文件的形式,我得到以下錯誤:在此之前多到
「」需要有字段中的值「公司」: 異常值可以使用多種關係。

請參閱下面的回溯。 錯誤信息對我來說沒有多大意義。唯一的m2m關係是bid_list,它是null = True,並且在保存時爲空。 在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]: [] 

當我嘗試跟蹤與debug toolbar的SQL語句,我只能看到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. 

settings.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}, 
    }, 
} 
+0

你對這個模型'Company'一個'company'場? – 2013-04-22 06:35:17

+0

例外值:在使用此多對多關係之前,「<公司:公司對象>」需要具有「公司」字段的值。 你模特沒有領域「公司」。在admin.py中是否有一切正常? – Hellpain 2013-04-22 07:42:56

+0

@Hellpain我也這麼認爲,但是admin.py不能簡單一些:'from company.models import Company admin.site.register(Company)'。奇怪的是,這些對象沒有被錯誤地保存在'django shelll'中。很奇怪。 – neurix 2013-04-22 08:11:27

回答

1

您正在使用自定義的用戶模型AUTH_PROFILE_MODULE = 'profile.UserProfile',但在代碼中,我想你使用本機的Django用戶。

我想你的模型應該像

class Company(models.Model): 
    user = models.OnetoOneField('profile.UserProfile') 
... 

更多https://docs.djangoproject.com/en/1.5/ref/contrib/auth/#django.contrib.auth.models.User.get_profile

+0

謝謝你的回答。按照您的建議切換用戶類,錯誤消失。然而,即使如此,管理頁面正在返回,對象已成功保存,表格爲空,並且沒有對象到達數據庫。你有什麼想法,爲什麼? – neurix 2013-04-22 11:04:01

+1

這很奇怪。你使用的是Postgre嗎?有幾個額外的配置爲Postgre。 https://docs.djangoproject.com/en/1.5/ref/databases/#postgresql-connection-settings 否則嘗試在sqlite上運行項目。我們必須看到問題 - 在數據庫或代碼 – Hellpain 2013-04-22 12:10:08

+0

謝謝你的提示切換到sqlite。它顯示問題必須與代碼,因爲錯誤仍然存​​在(我實際上再次看到原始錯誤消息)。 – neurix 2013-04-22 14:56:40

11

的問題與你如何使用你的意見辦。 我覺得你有一個實例ID之前使用: instance.add(many_to_many_instance)

所以先救你的模型:

instance.save() 
instance.add(many_to_many_instance) 
+0

是的,錯誤消息抱怨訪問一個不存在的數據庫對象。我投票給你。 – stanleyxu2005 2014-11-05 17:44:37

+0

我遇到了同樣的問題,你的回答激勵我去看看我的模型類中多對多字段的其他用法。就我而言,問題在於提及'clean'中的多對多字段。 – Bezewy 2015-11-17 21:24:26

相關問題