2012-02-16 16 views
0

我有一個Django視圖,應該保存包含三個字段集的CalendarEvent(模型實例),包括當前用戶的配置文件對象。該觀點得到@login_required保護,我登錄的超級用戶,然後叫得到該錯誤的觀點:在回溯如何在Django視圖中使用空用戶ID進行保存?

/Users/jonathan/pim/../pim/pim_calendar/views.py in save_calendar 
      date_padding = '' 
     regexp = weekday + ' ' + month + ' ' + date_padding + date + \ 
      ' ..:..:.. ... ' + year 
     event = pim_calendar.models.CalendarEvent() 
     event.when = regexp 
     event.description = description 
     event.user = request.user.get_profile() 
     event.save() 

。 (request.user應該是我登錄的超級用戶。)

我得到的錯誤是:

IntegrityError at /save_calendar 
pim_calendar_calendarevent.userprofile_id may not be NULL 
Request Method: POST 
Request URL: http://localhost:8000/save_calendar 
Django Version: 1.3.1 
Exception Type: IntegrityError 
Exception Value:  
pim_calendar_calendarevent.userprofile_id may not be NULL 
Exception Location: /usr/local/Cellar/python/2.7/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py in execute, line 234 
Python Executable: /usr/local/bin/python 
Python Version: 2.7.0 
Python Path:  
['/Users/jonathan/pim', 
'/usr/local/Cellar/python/2.7/lib/python2.7/site-packages/distribute-0.6.14-py2.7.egg', 
'/usr/local/Cellar/python/2.7/lib/python2.7/site-packages/pip-0.8.1-py2.7.egg', 
'/usr/local/Cellar/python/2.7/lib/python27.zip', 
'/usr/local/Cellar/python/2.7/lib/python2.7', 
'/usr/local/Cellar/python/2.7/lib/python2.7/plat-darwin', 
'/usr/local/Cellar/python/2.7/lib/python2.7/plat-mac', 
'/usr/local/Cellar/python/2.7/lib/python2.7/plat-mac/lib-scriptpackages', 
'/usr/local/Cellar/python/2.7/lib/python2.7/lib-tk', 
'/usr/local/Cellar/python/2.7/lib/python2.7/lib-old', 
'/usr/local/Cellar/python/2.7/lib/python2.7/lib-dynload', 
'/usr/local/Cellar/python/2.7/lib/python2.7/site-packages', 
'/usr/local/Cellar/python/2.7/lib/python2.7/site-packages/PIL', 
'/usr/local/lib/python2.7/site-packages', 
'/usr/local/Cellar/python/2.7/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg-info'] 
Server time: Thu, 16 Feb 2012 15:00:21 -0600 

如果我添加的event.save()調用之前,

 print repr(event.user) 

的控制檯顯示 「」 「<用戶配置:USERPROFILE對象> 」「」 上IntegrityError在崩潰之前。

有什麼建議嗎?

回答

3

從錯誤消息,它看起來像代替:

event.user = request.user.get_profile() 

你應該調用此:

event.userprofile = request.user.get_profile() 
0

除了什麼@jkbr說,你可能要考慮不拯救CalendarEvent對象中的UserProfile引用。

# Save event 
event = pim_calendar.models.CalendarEvent() 
event.user = request.user 
event.user.save() 

# Access the profile 
event = CalendarEvent.objects.get(...) 
the_userprofile = event.user.get_profile() 
:相反,只保存與CalendarEvent相關聯的用戶,然後通過訪問用戶配置
相關問題