且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为Django中的表单集中的字段设置默认值

更新时间:2023-01-31 22:08:26

使用初始数据实例化表单的成语是:

The idiom to instance a formset with initial data is:

data = {
     'form-TOTAL_FORMS': u'2',
     'form-INITIAL_FORMS': u'0',
     'form-MAX_NUM_FORMS': u'',
     'form-0-updated_by': u'user',
     'form-1-updated_by': u'user',
}

formset = LineItemsInlineFormSet(data)



更新: / h3>

由于 Jonny Buchanan 注意到,这种方法为您提供了一个绑定的表单,如果未提供所有必需的数据,将显示验证错误。如果不是您想要的,请创建您的表单传递自定义表单所需的设置为 django.forms.formsets.formset_factory()

Update:

As Jonny Buchanan noted, this approach gives you a bound formset, which will display validation errors if all required data is not provided. If it is not what you want, create your formset passing a custom Form with desired settings to django.forms.formsets.formset_factory().

updated_by 设置为当前登录的用户自动更新。如果这是你想要的:

It is common to set updated_by as the current logged-in user automagically upon update. If this is what you want:


  1. 省略表单中的 updated_by 字段;如果它是一个ModelFormset,则$
  2. updated_by 设置为当前用户;和

  3. 保存对象实例,现在使用默认的 commit = True

  1. omit the updated_by field in the form;
  2. save() with commit=False if it is a ModelFormset;
  3. set updated_by to current user; and
  4. save object instances, now with the default commit=True.

在管理员网站中,有一个方便的方法来进行内联:overrride ModelAdmin.save_formset

In the admin site there is a convenient way to do this with inlines: overrride ModelAdmin.save_formset.