[Django]-Django: check a last character in string

4👍

Karthikr’s answer is close. Ifequal is scheduled to be deprecated in future versions of Django, so you may want to use the method below. You also need to add a ‘:’ after the ‘-1’.

{% if doc.specialization.name|default:""|slice:"-1:" == "s" %}
  <h3> {{ doc.specialization.name|slice:":-1" }} </h3>
{% else %}
  <h3> {{ doc.specialization.name }} </h3>
{% endif %}

2👍

You cannot run python code in a django template. You can use a builtin filter for this:

{% ifequal doc.specialization.name|default:""|slice:"-1" "s" %}
    {# do your stuff #}
{% endifequal %}

The default is only a fallback for None values

Documentation on slice here

You could even use the with tag to avoid computing the same thing multiple times

0👍

You’re better off doing this in your view code than in a template. For example:

for doc in doc_records:
    if doc.specialization.name.endswith('s'):
        doc.specialization.name = doc.specialization.name[:-1]

But don’t save the record, assuming this is just for display purposes

👤dylrei

Leave a comment