Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/google-sheets/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在init上创建django表单_Django_Django Forms - Fatal编程技术网

在init上创建django表单

在init上创建django表单,django,django-forms,Django,Django Forms,如何在表单init函数中添加字段?e、 g.在下面的代码中,我想添加一个配置文件字段 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函数中添加字段?e、 g.在下面的代码中,我想添加一个配置文件字段

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
我知道我可以把它添加到班级职员表的下方。。。。行,但我希望这是动态的,取决于传入的用户,所以不能这样做


谢谢

只需切换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

可能重复其中的一些:,尤其是和重复的:您能提供一个我们可以在哪里使用self.fields的参考吗