Model formset saving with form.save(commit=False)

954 views
Skip to first unread message

Paul

unread,
Jul 28, 2009, 3:34:23 AM7/28/09
to Django users
Hello,

I understand that Django won't let you save 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?

Thanks in advance!
Paul

Paul

unread,
Jul 28, 2009, 7:10:57 PM7/28/09
to Django users
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()

The reason I just didn't do:

if formset.is_valid():
formset.save()

is because I wanted to see what the POST was giving me. And it turns
out that I should have included all the hidden fields in my manually
created form in my template. So I had to include this in my template
too to get all the POST data necessary to change the data in my model:

{% for hid in form.hidden_fields %}
{{hid}}
{% endfor %}
Reply all
Reply to author
Forward
0 new messages