为Django中的表单集中的字段设置默认值 [英] Setting a default value for a field in a formset in Django
问题描述
在Django中的表单集中,我们如何为需要http会话的值的字段设置默认值?由于需要获取该值的会话,因此我们无法在模型类本身中设置默认值。而且,在保存在视图函数中之前,我无法理解如何在表单集中的每个表单中明确设置值。
In a formset in Django, how do we set a default value for a field which needs a value from the http session? Since a session is required to get the value, we cannot set a default value in the model class itself. And I am not able to understand how to explicitly set the value in each form in the formset before saving in the view function.
在构造中设置初始属性FormSet将工作,但无论什么原因,我收到一个编译错误。代码如下:
Setting the initial attribute in the construction of the FormSet would work but for whatever reason, I get a compilation error. The code is like this:
formset = LineItemsInlineFormSet(initial=[{'updated_by':'user'}])
编译错误是: init ()得到一个意想不到的关键字参数'initial'
The compilation error is: init() got an unexpected keyword argument 'initial'
我正在使用Django 1.1.1
I am using Django 1.1.1
任何见解将不胜感激。
感谢提前。
Any insight will be appreciated. Thanks in Advance.
推荐答案
使用初始数据实例化表单的成语是:
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:
- 省略表单中的
updated_by
字段;如果它是一个ModelFormset,则$
- 将
updated_by
设置为当前用户;和
- 保存对象实例,现在使用默认的
commit = True
。
- 将
- omit the
updated_by
field in the form; save()
withcommit=False
if it is a ModelFormset;- set
updated_by
to current user; and - 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.
这篇关于为Django中的表单集中的字段设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!