django - how to reuse a template for nearly identical models?

点点圈 提交于 2019-12-05 21:16:26

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!