[Django]-Django โ€“ how to reuse a template for nearly identical models?

5๐Ÿ‘

โœ…

If you create a property in your models that indicates the specific field of interest for each type, that would let you use one variable in a template. Example:

class addressbook(models.Model):
    name = models.CharField(max_length=50)

class company(addressbook):
    address = models.CharField(max_length=50)

    @property
    def display_field(self):
        return self.address

class contact(addressbook):
    telephone = models.CharField(max_length=30)

    @property
    def display_field(self):
        return self.telephone

Now in your template you can use {{ blah.display_field }} and it will print the value you want, depending on the object type.

๐Ÿ‘คDan Breen

Leave a comment