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

假装没事ソ 提交于 2019-12-07 15:59:14

问题


Still fairly new to django and python.

I've defined two nearly identical models that inherit from a base class:

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

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

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

I want to do very similar things with company and contact objects. However in my templates it looks like I need to use separate templates for each object since to access the members in the object I have to use something like

{{ blah.name }} {{ blah.address}}

in one but

{{ blah.name }} {{ blah.telephone}} 

in the other.

All this repetition makes me suspicious. Is there some python or django template syntax that would allow me to reuse a single template (with some sort of built in intelligence) with both models?

Thanks for your help! W.


回答1:


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.



来源:https://stackoverflow.com/questions/7906296/django-how-to-reuse-a-template-for-nearly-identical-models

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