I have a Python object that is an instance of a subclass of container. So this object, x, can behave like x['name']. This object also has methods, say x.bar().
How do I call x.bar from a Django template? In the template x.bar will always be evaluated as x['bar'] first, which gives None.
The best I can think of is to create an object shadowing x, that does not have getitem. But I can’t delattr __getitem__.
Any better ideas? Short of passing in results of those calls manually in context or a template tag.
Thanks.
This is a fundamental flaw in the way Django templates do expression evaluation. Look at the template tag
{% expr -arbitrary-python-expression- %}for a workaround. E.g.{% expr x.bar(1,2,3) as snort %}gives you a new variable in the current Context namedsnort.Alternatively, you could try Jinja2 templates. They are very close to Django’s, but they allow full Python.
Note: Jinja2 is not the same templating system as Django’s, and if you are using any page-embedded django app’s that depend on the templating system, this may break them. That is not true for the
{% expr %}tag.