我想以编程方式排除表单中的字段。 目前我有这个:
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
字段?
答案 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']