Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different initial data for each form in a Django formset

Is it possible to prepopulate a formset with different data for each row? I'd like to put some information in hidden fields from a previous view.

According to the docs you can only set initial across the board.

like image 278
cerial Avatar asked Dec 13 '09 21:12

cerial


1 Answers

If you made the same mistake as me, you've slightly mistaken the documentation.

When I first saw this example...

formset = ArticleFormSet(initial=[  {'title': 'Django is now open source',   'pub_date': datetime.date.today(),} ]) 

I assumed that each form is given the same set of initial data based on a dictionary.

However, if you look carefully you'll see that the formset is actually being passed a list of dictionaries.

In order to set different initial values for each form in a formset then, you just need to pass a list of dictionaries containing the different data.

Formset = formset_factory(SomeForm, extra=len(some_objects) some_formset = FormSet(initial=[{'id': x.id} for x in some_objects]) 
like image 99
Alistair Avatar answered Sep 21 '22 12:09

Alistair