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

2

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Can you provide a reference for where we can use self.fields

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.