如何在Django视图中使用null用户ID进行保存?

时间:2012-02-16 21:14:36

标签: python django django-models django-views

我有一个Django视图,它应该保存一个CalendarEvent(一个模型实例),其中包含三个字段集,包括当前用户的配置文件对象。视图受@login_required保护,我以超级用户身份登录,然后调用视图获取错误:

    /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)

控制台在IntegrityError崩溃之前显示“”< UserProfile:UserProfile对象>“”“。

有什么建议吗?

2 个答案:

答案 0 :(得分:3)

从错误消息看起来而不是:

    event.user = request.user.get_profile()

你应该这样称呼:

    event.userprofile = request.user.get_profile()

答案 1 :(得分:0)

除了@jkbr所说的,您可能还想考虑不在CalendarEvent对象中保存UserProfile引用。相反,只需保存与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()