django-如何为几乎相同的模型重用模板? [英] django - how to reuse a template for nearly identical models?
问题描述
对于django和python还是很新的。
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}}
{{ blah.name }} {{ blah.telephone}}
其他。
所有这些重复使我感到怀疑。是否有一些python或django模板语法可以让我在两个模型中重用单个模板(具有某种内置的智能功能)?
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?
感谢您的帮助!
W。
Thanks for your help! W.
推荐答案
如果您在模型中创建一个属性,该属性指示每种类型的特定关注领域,这样您就可以在模板中使用一个变量。示例:
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
现在您可以在模板中使用{{等等。 display_field}},它将根据对象类型显示所需的值。
Now in your template you can use {{ blah.display_field }} and it will print the value you want, depending on the object type.
这篇关于django-如何为几乎相同的模型重用模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!