简体   繁体   中英

How can I create Django ModelForm for an abstract Model?

I have an abstract model that all my other models inherit from, it looks like this.

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

I then have a bunch of other models that inherit from this model, with something along these lines...

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)

I want to create a Django model form for nearly all of my custom models that look similar to ExampleModel, but I always want the fields in SupremeModel to be excluded in the form...

How can I create a ModelForm that can be used to inherit the exclude parameters that will hide creator,created,deleted, and modified but show all of the other fields (in this case name and description or title and location).

you may try this

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM