Django表单中每个表单的不同初始数据 [英] Different initial data for each form in a Django formset

查看:96
本文介绍了Django表单中每个表单的不同初始数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以为每行预填充具有不同数据的表单?

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.

推荐答案

如果您与我同样的错误,您稍微误认为文件。

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

这篇关于Django表单中每个表单的不同初始数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆