如何在Django中保存内联formset模型? [英] How to save inline formset models in Django?

查看:660
本文介绍了如何在Django中保存内联formset模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Formsets have a .save() method, and the documentation says to save in views like this:

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保存现有的模型时,我会得到异常。父母实际上被保存到数据库中,并且在保存相关模型时发生异常。

I am following this, and it works when the parent is created, but I'm getting an exception in Django when it is saving existing models. The parent actually is saved to the database and the exception occurs when saving related models.

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来源度过了一段时间,但找不到任何东西。我需要遍历每个表单,并且只保存已经更改的模型吗?

I spent some time in Django source but can't find anything there. Do I need to iterate through each formset and only save models that have changed?

推荐答案

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

I discovered my problem, and it's embarrassing.

在父模型表单中,我在Meta类中有 exclude =('...',)并且排除的字段之一对于inline_formsets中的关系至关重要。所以,我删除了排除并忽略了模板中的这些字段。

In the parent model form I had exclude = ('...',) in the Meta class, and one of the excluded fields was critical for the relations in the inline_formsets. So, I've removed the excludes and ignoring those fields in the template.

这篇关于如何在Django中保存内联formset模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆