22

How can I add a field in the form init function? e.g. in the code below I want to add a profile field.

class StaffForm(forms.ModelForm):
    def __init__(self, user, *args, **kwargs):
        if user.pk == 1:
            self.fields['profile'] = forms.CharField(max_length=200)

        super(StaffForm, self).__init__(*args, **kwargs)

    class Meta:
        model = Staff

I know I can add it just below the class StaffForm.... line but I want this to be dynamic depending on what user is passed in so can't do it this way.

Thanks

John
  • 21,047
  • 43
  • 114
  • 155
  • 3
    *Possibly duplicate of some of these:* http://stackoverflow.com/search?q=django+dynamic+form , Especially http://stackoverflow.com/questions/2390000/dynamic-django-forms-variable-fields and http://stackoverflow.com/questions/2506136/storing-dynamic-fields-in-django-forms – Felix Kling Apr 08 '10 at 12:51
  • duplicated: https://stackoverflow.com/questions/22390416/setting-initial-django-form-field-value-in-the-init-method – Julio Marins Jul 31 '17 at 19:59

1 Answers1

39

Just need to switch the init function round so that super is called before adding anymore fields.

class StaffForm(forms.ModelForm):
    def __init__(self, user, *args, **kwargs):
        super(StaffForm, self).__init__(*args, **kwargs)

        if user.pk == 1:
            self.fields['profile'] = forms.CharField(max_length=200)
            self.fields['profile'].initial = 'whatever you want'
    class Meta:
        model = Staff
Ilian Iliev
  • 3,217
  • 4
  • 26
  • 51
John
  • 21,047
  • 43
  • 114
  • 155