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

查看:15
本文介绍了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天全站免登陆