django form creation on init

后端 未结 1 896
故里飘歌
故里飘歌 2021-02-01 18:25

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, u         


        
1条回答
  •  南笙
    南笙 (楼主)
    2021-02-01 19:11

    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
    

    0 讨论(0)
提交回复
热议问题