Formsets有一个.save()方法,documentation表示保存在这样的视图中:
if request.method == "POST":
formset = BookInlineFormSet(request.POST, request.FILES, instance=author)
if formset.is_valid():
formset.save()
# Do something.
else:
formset = BookInlineFormSet(instance=author)
我正在关注这个,它在创建父项时有效,但我在Django中保存现有模型时遇到异常。父实际上会保存到数据库中,并在保存相关模型时发生异常。
KeyError at /bcdetails/NewProds/1/
None
Request Method: POST
Request URL: http://rdif.local/bcdetails/NewProds/1/
Exception Type: KeyError
Exception Value:
None
Exception Location: /usr/lib/python2.5/site-packages/django/forms/models.py in save_existing_objects, line 403
Python Executable: /usr/bin/python
Python Version: 2.5.2
Python Path: ['/usr/lib/python2.5/site-packages/paramiko-1.7.4-py2.5.egg', '/usr/lib/python2.5/site-packages/Fabric-0.0.9-py2.5.egg', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/local/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/Numeric', '/usr/lib/python2.5/site-packages/PIL', '/usr/lib/python2.5/site-packages/gst-0.10', '/var/lib/python-support/python2.5', '/usr/lib/python2.5/site-packages/gtk-2.0', '/var/lib/python-support/python2.5/gtk-2.0', '/usr/lib/site-python', '/home/www/rdif.com/test/']
Server time: Wed, 7 Jan 2009 23:18:19 -0700
我花了一些时间在Django源代码,但在那里找不到任何东西。我是否需要遍历每个formset并仅保存已更改的模型?
答案 0 :(得分:4)
我发现了我的问题,而且令人尴尬。
在父模型表单中,我在Meta类中有exclude = ('...',)
,其中一个排除字段对于inline_formsets中的关系至关重要。所以,我删除了排除并忽略了模板中的那些字段。