Reputation: 591
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.
Upvotes: 3
Views: 377
Reputation: 12924
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.
Upvotes: 5