Python – How do I save an inline form set model in Django?

How do I save an inline form set model in Django?… here is a solution to the problem.

How do I save an inline form set model in Django?

Formsets have a .save() method, and documentation says to be saved like this View:

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’m looking at this, it works when creating parent, but I’m getting an exception in Django when saving an existing model. parent is actually saved to the database, and an exception occurs when saving the related model.

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 the Django source code but couldn’t find anything there. Do I need to iterate through each form set and save only the changed model?

Solution

I found my problem and it was embarrassing.

In the parent model form, I have exclude = ('...',) in the Meta class, where one of the excluded fields is critical for relationships in inline_formsets. So I removed the exclusions and ignored those fields in the template.

Related Problems and Solutions