如何为抽象模型创建Django ModelForm?

4
我有一个抽象模型,所有其他模型都继承自它,它看起来像这样:

class SupremeModel(models.Model):
    creator = models.ForeignKey(User, related_name="%(class)s_creator")
    created = models.DateTimeField(null=True, blank=True)
    deleted = models.BooleanField(default=False)
    modified = models.DateTimeField(null=True,blank=True)

    class Meta:
        abstract = True

我有一堆其他模型继承自这个模型,类似于以下内容...
class ExampleModel(SupremeModel):
    name = models.TextField(null=False, blank=False)
    description = models.TextField(null=False, blank=False)

class AnotherModel(SupremeModel):
    title = models.TextField(null=False, blank=False)
    location = models.TextField(null=False, blank=False)

我希望为几乎所有类似于ExampleModel的自定义模型创建一个Django模型表单,但我总是希望在表单中排除SupremeModel中的字段...
如何创建一个ModelForm,以继承exclude参数,隐藏creator,created,deleted和modified,但显示所有其他字段(在此示例中为name和description或title和location)。
1个回答

7

你可以试试这个

class ExcludedModelForm(ModelForm):
    class Meta:
        exclude = ['creator', 'created', 'deleted', 'modified']

class ExampleModelForm(ExcludedModelForm):
    class Meta(ExcludedModelForm.Meta):
        model = ExampleModel

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