Different initial data for each form in a Django formset

前端 未结 4 1270
灰色年华
灰色年华 2020-12-07 17:37

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 d

4条回答
  •  粉色の甜心
    2020-12-07 18:35

    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])
    

提交回复
热议问题