[Answered ]-Dynamically Display field values in Django template (object.x)

1πŸ‘

βœ…

It sounds like you want to do something along the lines of:

# in the views.py:
field = 'business'


{# in the template: #}
{{ object.field }}

and have the value of object.business appear in the output. This isn’t possible with the Django template language out of the box.

There are snippets that define template filters you can use to accomplish this though: http://www.djangosnippets.org/snippets/1412/

1πŸ‘

As mentioned above, you can do this with a custom template filter.

For example:

@register.filter(name='get_attr')
def get_attr(obj, field_name):
    if isinstance(obj, dict):
        return obj.get(field_name)
    return getattr(obj, field_name)

Then, using it in your template:

{{ obj|get_attr:'business' }}
πŸ‘€toast38coza

Leave a comment