在init上创建django表单

Joh*_*ohn 21 django django-forms

如何在表单init函数中添加字段?例如,在下面的代码中,我想添加一个配置文件字段.

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
Run Code Online (Sandbox Code Playgroud)

我知道我可以在类StaffForm ....行下面添加它但我希望这是动态的,具体取决于传入的用户,所以不能这样做.

谢谢

Joh*_*ohn 37

只需要转换init函数,以便在添加更多字段之前调用super.

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
Run Code Online (Sandbox Code Playgroud)