在init上创建django表单 [英] django form creation on init

查看:145
本文介绍了在init上创建django表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在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
/ pre>

我知道我可以将它添加到StaffForm ....类的下面,但是我希望这是动态的,具体取决于用户传入的内容,这样做。



谢谢

解决方案

只需要切换init函数,以便在添加任何字段之前调用super。

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

if user.pk == 1:
self.fields ['pro文件'] = forms.CharField(max_length = 200)
self.fields ['profile']。initial ='无论你想要什么'
class Meta:
model = Staff


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

解决方案

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

这篇关于在init上创建django表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆