Python’s getattr() method is useful when you don’t know the name of a certain attribute in advance.
This functionality would also come in handy in templates, but I’ve never figured out a way to do it. Is there a built-in tag or non-built-in tag that can perform dynamic attribute lookups?
I also had to write this code as a custom template tag recently. To handle all look-up scenarios, it first does a standard attribute look-up, then tries to do a dictionary look-up, then tries a getitem lookup (for lists to work), then follows standard Django template behavior when an object is not found.
(updated 2009-08-26 to now handle list index lookups as well)
Template usage: