3

Formsets 有一个 .save() 方法,文档说要保存在这样的视图中:

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 源代码中花了一些时间,但在那里找不到任何东西。我是否需要遍历每个表单集并仅保存已更改的模型?

4

1 回答 1

4

我发现了我的问题,这很尴尬。

在 Meta 类中的父模型表单exclude = ('...',)中,其中一个被排除的字段对于 inline_formsets 中的关系至关重要。因此,我删除了排除项并忽略了模板中的那些字段。

于 2009-01-08T10:27:55.740 回答