简体   繁体   中英

Django template {{ item.get_FOO_display }} using only jinja2 without django

I use Django. I also use standalone Jinja2 to build email body from django models.

I have model with choice field and I would like to get its display value from the model instance.

In django template, it is easy, for example:

{{ form.get_foo_display }}.

However, it does not work if is it outside of the django template. My code using jinja2 is:

Trip participation:\t{{ item.get_event_trip_display }}

where item is model instance and event_trip is choice field (the {{ item.event_trip }} works ok)

However the get_event_trip_display is rendered as:

Trip participation: <bound method curry.<locals>._curried of <Registration: John Doe>>

Known solutions:

  1. Use {% if ... %} block to manually select the choice.

  2. Append the instance with new attributes in Python code:

    item.trip_parictipation_display = item.get_trip_participation_display()

My question:

Is there simpler way hot to call the function directly in jinja2? (I have a lot of fields like that)

get_event_trip_display is a method. Django templates automatically call methods, but Jinja2 templates don't. You need to call it explicitly:

{{ item.get_event_trip_display() }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM