简体   繁体   中英

How to save inline formset models in Django?

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)

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM