添加额外的字段到ModelForm [英] add extra field to ModelForm
本文介绍了添加额外的字段到ModelForm的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
类形式(forms.ModelForm):$ b我添加了一个额外的字段到Django ModelForm $ b extra_field = forms.CharField(label =机构名称)
class Meta:
model = db_institutionInstitution
fields = ['conn_kind','time','inst_name2']
表单实际工作正常,但我不能预先填写。我使用它在一个 modelformset_factory
中:
formset = modelformset_factory(db_institutionInstitution, form = form)
我手动运行一个查询器,并添加额外的字典所需的条目表单中的表单。但是,当我打电话:
formset1 = formset(prefix ='brch',queryset = qs1)
extra_field
未按预期预先填充(其余工作正常)
任何人都可以帮忙?
解决方案
一个默认值。
extra_field = forms.CharField(label ='Institution',default =harvard)
如果要动态设置值:
def __init __(self,* args,** kwargs):
super(form,self).__ init(* args,** kwargs)
self.fields ['extra_field']。initial =harvard
I am adding an extra field to a Django ModelForm like that:
class form(forms.ModelForm):
extra_field = forms.CharField(label='Name of Institution')
class Meta:
model = db_institutionInstitution
fields = ['conn_kind','time','inst_name2']
The form is actually working fine, but I cant prepopulate it. I use it in a modelformset_factory
:
formset = modelformset_factory(db_institutionInstitution,form=form)
I manually run through a queryset and add the entry in the dictionary needed for the additional form in the formset. However, when I call:
formset1 = formset(prefix='brch',queryset=qs1)
the extra_field
is not prepopulated as intended (the rest is working fine).
Can anyone help?
解决方案
If you want to set a default.
extra_field = forms.CharField(label='Name of Institution', default="harvard")
If you want to dynamically set a value:
def __init__(self, *args, **kwargs):
super(form,self).__init(*args, **kwargs)
self.fields['extra_field'].initial = "harvard"
这篇关于添加额外的字段到ModelForm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文