add extra field to ModelForm
Asked Answered
U

1

18

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?

Unreserved answered 10/6, 2015 at 15:55 Comment(0)
P
19

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 put it on form initialization:

def __init__(self, *args, **kwargs):
    super(form, self).__init__(*args, **kwargs)
    self.fields['extra_field'].initial = "harvard"
Propst answered 10/6, 2015 at 17:33 Comment(4)
"default" should be "initial"Aalesund
AttributeError: module 'django.forms' has no attribute 'Charfield'. Anyone knows how this answer will work in django 2.1?Agentive
Has 'CharField'Amersham
if i do this my form.is_valid() always return falseFare

© 2022 - 2024 — McMap. All rights reserved.