[formsets] Initial Values to an inline_formset() instance
576 views
Skip to first unread message
Nikhil Somaru
unread,
Jun 17, 2011, 6:08:35 AM6/17/11
Reply to author
Sign in to reply to author
Forward
Sign in to forward
Delete
You do not have permission to delete messages in this group
Copy link
Report message
Show original message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to django...@googlegroups.com
Hi,
PURPOSE: Mimic the admin "inline" functionality (with ForeignKey relationships) in one of my own forms without using Javascript (because I don't know it)
My Solution: Inline Formset via inline_formset()
However,
inline_formset() does not accept initial as an argument
This is after the form has been submitted once and I want to create new forms in the formsets while still keeping the data already entered, waiting to be edited
I am using the following workaround in the mean time: (the entire view may be found here: http://dpaste.com/hold/555463/)
elif 'more_items' in request.POST: order = form.save(commit=False) # models.Order instances = formset.save(commit=False) # models.OrderItem(s) for instance in instances: initial_data.append({'item': instance.item, 'quantity_requested': instance.quantity_requested, } ) formset = OrderFormset() #created via inline_formset() for subform, data in zip(formset.forms, initial_data): subform.initial = data # render_to_response....
The problem is, this limits me to a total number of forms as defined in the extra field passed to inline_formset().
Any improvements or totally new solutions are welcome! My Python/Django knowledge is beginner-intermediate (leaning towards beginner)
-- Yours,
Nikhil Somaru
Nikhil Somaru
unread,
Jun 17, 2011, 6:48:21 AM6/17/11
Reply to author
Sign in to reply to author
Forward
Sign in to forward
Delete
You do not have permission to delete messages in this group
Copy link
Report message
Show original message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to django...@googlegroups.com
Hi,
This is the hack-a-round that I figured out:
formset = OrderFormset(request.POST) #created earlier with inline_formset()
# now we recreate it to have the submitted number of forms+3 OrderFormset = inlineformset_factory(Order, OrderItem, extra=len(formset.forms)+3) formset = OrderFormset() # populate the forms # initial_data is a list of dictionaries created from POST data # dict keys are field names
for subform, data in zip(formset.forms, initial_data): subform.initial = data
I know this is inelegant and probably uses more memory than it should, but it works. Are there any other, more elegant solutions?