Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Building on Antony Vennard's answer, I am not sure what version of python/django he is using but I could not get the generator to work in the curry method either. I am currently on python2.7.3 and django1.5.1. Instead of using a custom Generator, I ended up using the built-in <code>iter()</code> on a list of things to create an iterator and passing the iterator itself in the curry method and calling <code>next()</code> on it in the <code>Form</code> <code>__init__()</code>. Here is my solution:</p> <pre><code># Build the Formset: my_iterator = iter(my_list_of_things) # Each list item will correspond to a form. Formset = formset_factory(MyForm, extra=len(my_list_of_things)) Formset.form = staticmethod(curry(MyForm, item_iterator=my_iterator)) </code></pre> <p>And in the form:</p> <pre><code># forms.py class MyForm(forms.Form): def __init__(self, *args, **kwargs): # Calling next() on the iterator/generator here: list_item = kwargs.pop('item_iterator').next() # Now you can assign whatever you passed in to an attribute # on one of the form elements. self.fields['my_field'].initial = list_item </code></pre> <p>Some Key things I found were that you need to either specify an 'extra' value in the <code>formset_factory</code> or use the <code>initial</code> kwarg on the formset to specify a list that corresponds to the list you pass to the iterator (In above example I pass the <code>len()</code> of the my_list_of_things list to 'extra' kwarg to formset_factory). This is necessary to actually create a number of forms in the formset.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload