动态删除django模型表单中字段的排除项

时间:2011-02-28 19:14:16

标签: django-forms

我想以编程方式启用默认排除的字段...

模型:

class MyModel(models.Model):
    name = models.CharField(max_length=100)
    an_excluded_field = models.TextField()
    my_bool = models.BooleanField(default=False) # this is the field to conditionally enable...

形式:

class MyModelForm(ModelForm):
    class Meta:
        model = EmailTemplate
        excludes = ('an_excluded_field', 'my_bool')

我想做这样的事情(或者那样的事情......):

form = MyModelForm(enable_my_bool=True)

这几乎就像这篇文章(我希望默认排除该字段): How can I exclude a declared field in ModelForm in form's subclass?

2 个答案:

答案 0 :(得分:5)

1)您可以定义表单的第二个版本:

class MyExcludedModelForm(MyModelForm):
    class Meta:
        excludes = ('my_bool',) # or could use fields in similar manner

2)你可以覆盖表单的构造函数:
(与您引用的其他SO帖子中描述的相同)

class MyModelForm(ModelForm):
    def __init__(self, *args, **kwargs):
        if not kwargs.get('enable_my_bool', false):
            self.fields.pop('my_bool')
        super(MyModelForm, self).__init__(*args, **kwargs) # maybe move up two lines? (see SO comments)

答案 1 :(得分:0)

如果覆盖构造函数,那么在调用超类构造函数(如mgalgs)之前需要pop来自kwargs的值:

def __init__(self, *args, **kwargs):
    enable_my_bool = kwargs.pop('enable_my_bool', True) # True is the default
    super(MyModelForm, self).__init__(*args, **kwargs)
    if not enable_my_bool:
        self.fields.pop('my_bool')