从Django ModelForm动态排除字段

时间:2018-05-29 15:22:08

标签: python django python-3.x django-2.0

我想以编程方式排除表单中的字段。 目前我有这个:

class RandomForm(BaseForm):
    def __init__(self, *args, **kwargs):

        # This doesn't work
        if kwargs["instance"] is None:
            self._meta.exclude = ("active",)

        super(ServiceForm, self).__init__(*args, **kwargs)

        # This doesn't work either
        if kwargs["instance"] is None:
            self._meta.exclude = ("active",)

    class Meta:
        model = models.Service
        fields = (...some fields...)

如何在创建新模型时排除active字段?

2 个答案:

答案 0 :(得分:7)

你可以这样解决:

class RandomForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(RandomForm, self).__init__(*args, **kwargs)
        if not self.instance:
            self.fields.pop('active')

    class Meta:
        model = models.Service
        fields = (...some fields...)

答案 1 :(得分:-1)

Django ModelForm提供exclude属性。你试过了吗?

class RandomForm(ModelForm):

    class Meta:
        model = models.Service
        exclude = ['is_active']