从Django ModelForm动态排除字段

ale*_*nst 7 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...)
Run Code Online (Sandbox Code Playgroud)

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

nev*_*ner 8

你可以这样解决:

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...)
Run Code Online (Sandbox Code Playgroud)