django - 如何为几乎相同的模型重用模板?
对于 django 和 python 来说还是相当新的。
我定义了两个几乎相同的模型,它们从基类继承:
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)
我想对公司和联系人对象执行非常相似的操作。然而,在我的模板中,看起来我需要为每个对象使用单独的模板,因为要访问对象中的成员,我必须
{{ blah.name }} {{ blah.address}}
在一个对象中
{{ blah.name }} {{ blah.telephone}}
使用类似于在另一个对象中使用的内容。
所有这些重复让我产生怀疑。是否有一些 python 或 django 模板语法允许我在两个模型中重用单个模板(具有某种内置智能)?
感谢您的帮助! W.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您在模型中创建一个属性来指示每种类型感兴趣的特定字段,那么您将可以在模板中使用一个变量。示例:
现在,您可以在模板中使用 {{ blah.display_field }},它将根据对象类型打印您想要的值。
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:
Now in your template you can use {{ blah.display_field }} and it will print the value you want, depending on the object type.