我在formset中部署的模型中隐藏字段的初始值存在问题。只是第一个表单在隐藏字段中具有初始值,而其他表单为空。
modelForm是:
class md_changelogFormModel(forms.ModelForm):
post_docs = forms.CharField(widget=forms.HiddenInput(),
initial="READY_FOR_RUN")
# Other fields
class Meta:
model = md_changelog
fields = '__all__'
在基于BaseInlineFormSet的表单中使用相同的模型md_changelog:
class md_changelogForm(BaseInlineFormSet)
class Meta:
model = md_changelog
fields = '__all__'
使用inlineformset_factory创建一个formset类:
md_changelogFormSet = inlineformset_factory(md_orderlog, md_changelog,
form=md_changelogFormModel,
formset=md_changelogForm,
extra=1, max_num=20)
formset类在基于类的视图中实例化:
def get(self, request, *args, **kwargs):
"""
Handles GET requests and instantiates blank versions of the form
and its inline formsets.
"""
self.object = None
form_class = self.get_form_class()
form = self.get_form(form_class)
md_changelog_form = md_changelogFormSet(initial=[{'post_docs':'READY_FOR_RUN'}])
return self.render_to_response(
self.get_context_data(form=form,
md_changelog_form=md_changelog_form))
问题是当post函数收到request.POST时,只有formset数据的第一种形式的post_docs hidden字段用初始值填充,其他没有。
如何初始化其他表格?
谢谢!
答案 0 :(得分:0)
如果您需要为给定表单字段中的所有表单提供初始值,请查看文档:{{3}}
因此,在我看来,为了初始化具有相同初始日期的所有3个字段,您应该将代码更改为:
def get(self, request, *args, **kwargs):
"""
Handles GET requests and instantiates blank versions of the form
and its inline formsets.
"""
self.object = None
form_class = self.get_form_class()
form = self.get_form(form_class)
md_changelog_form = md_changelogFormSet(initial=[
{'post_docs':'READY_FOR_RUN'},
{'post_docs':'READY_FOR_RUN'},
{'post_docs':'READY_FOR_RUN'},
])
return self.render_to_response(self.get_context_data(form=form, md_changelog_form=md_changelog_form))
希望有所帮助!