James L.
James L.

Reputation: 1153

Django: check a last character in string

I have this string doc.specalization.name from my views. If it does end with an s, I want to remove the s.

I tried this code but i get Could not parse the remainder: '('s')' from 'doc.specialization.name.endswith('s')'

 {% if doc.specialization.name.endswith('s') %}
        <h3> {{doc.specialization.name|slice:":-1"}} </h3>   
 {% endif %}

Upvotes: 4

Views: 5108

Answers (3)

sv_rancher
sv_rancher

Reputation: 161

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 %}

Upvotes: 4

karthikr
karthikr

Reputation: 99620

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

Upvotes: 2

dylrei
dylrei

Reputation: 1738

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

Upvotes: 0

Related Questions