views:

592

answers:

2

Hello,

I understand that Django won't let you save a incomplete fields in a single form created from a Model unless you do this:

tmpform = form.save(commit=False)
tmpform.foo = form.cleaned_data['foo']
tmpform.save()

So I want to do this kind of thing with forms in a formset - I am trying to to iterate through all the fields for each form in the formset. But the problem is that I'm not sure exactly how to iterate through all the fields of each form in the formset. I tried this:

for form in formset.forms:
  for name, field in form.fields.items():
    tmpform = form.save(commit=False)
    tmpform.field[name] = form.cleaned_data[name] # doesn't work, I get an error
    tmpform.save()

But I only get the ERROR message:

'FooForm' object has no attribute 'field'.

My question is: how do I use form.save(commit=False) properly given that I have multiple fields in a form with different field names?

+1  A: 

Try using setattr since you don't know the name of the field.

setattr(tmpform, field, form.cleaned_data[name])
seth
Thank you for pointing me in the right direction!
Paul
You are welcome.
seth
A: 

After fiddling around I think I found the syntax that seems to work for my purposes:

if formset.is_valid():
   for form in formset.forms:
     tmpform = form.save(commit=False)
     for field in form:
        if not field.form.is_bound:
          data = field.form.initial.get(field.name,
                                field.field.initial)
          if callable(data):
            data = data()
        else:
          data = field.data

        setattr(tmpform, field.name, data)
        print "fieldname: %s - value: %s" %(field.name,data)

     tmpform.save()
Paul