Ricky
Ricky

Reputation: 883

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

Upvotes: 4

Views: 4400

Answers (1)

Jerry Day
Jerry Day

Reputation: 376

you may try this

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

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

Upvotes: 8

Related Questions