动态从Django ModelForm中排除字段

14
我想在我的表单中通过程序排除一个字段。 目前我的代码是这样的:
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 字段?


只是为了澄清一下:不工作的意思是即使执行了self._meta.exclude = ("active",)这行代码,该字段仍然会在表单中出现?还是你遇到了错误? - Ralf
这只是一个打字错误还是 RandomForm 真的在从 ServiceForm 调用超类方法? - Ralf
@Ralf 确实如此。"不起作用"意味着该字段仍在显示。另外,是的,那是一个打字错误。 - alexandernst
2个回答

13

您可以这样解决:

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...)

这将覆盖我的模型中的verbose_name、默认值等内容。 - alexandernst
@alexandernst 我没有测试的机会,但是尝试一下 if not self.instance: self.fields.pop('active')。你还应该将 active 添加到元数据的字段中。 - neverwalkaloner
1
在Django 3.2中,即使是新实例,if not self.instance也为false。将条件更改为if not self.instance.id将实现预期的行为。 - kyuden

-5
Django ModelForm提供了exclude属性。你试过这个吗?
class RandomForm(ModelForm):

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

1
我没有看到“dv”,但我认为OP的意思是根据某些属性(例如实例是否已存在),表单应该以不同的方式呈现,这样我们就可以重复使用相同的表单,但它将显示不同的字段。 - Willem Van Onsem

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接