add extra field to ModelForm

房东的猫 提交于 2020-01-01 07:52:42

问题


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?


回答1:


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"


来源:https://stackoverflow.com/questions/30761411/add-extra-field-to-modelform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!