向ModelForm添加额外的字段(add extra field to ModelForm)

编程入门 行业动态 更新时间:2024-10-28 06:30:07
向ModelForm添加额外的字段(add extra field to ModelForm)

我正在给Django ModelForm添加一个额外的字段:

class form(forms.ModelForm): extra_field = forms.CharField(label='Name of Institution') class Meta: model = db_institutionInstitution fields = ['conn_kind','time','inst_name2']

表格实际上工作正常,但我不能预先填充它。 我在modelformset_factory使用它:

formset = modelformset_factory(db_institutionInstitution,form=form)

我手动运行一个查询集,并在formset中的附加表单所需的字典中添加条目。 但是,当我打电话时:

formset1 = formset(prefix='brch',queryset=qs1)

extra_field没有像预期的那样预填充(其余的工作正常)。

谁能帮忙?

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?

最满意答案

如果你想设置一个默认值。

extra_field = forms.CharField(label='Name of Institution', default="harvard")

如果你想动态设置一个值:

def __init__(self, *args, **kwargs): super(form,self).__init(*args, **kwargs) self.fields['extra_field'].initial = "harvard"

If you want to set a default.

extra_field = forms.CharField(label='Name of Institution', initial="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"

更多推荐

本文发布于:2023-08-02 16:56:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1378985.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   ModelForm   add   field   extra

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!