[Django]-Django get first part of a string

5đź‘Ť

âś…

You could try:

{% if run.status|truncatechars:5 == 'error...' %}

(See truncatechars in the Django docs)

Although I might say, as an overall point, you shouldn’t be putting this kind of logic in your Django templates (views in other frameworks). You want to put this into the Django view (controller in other framerworks). Meaning, you would something like this in your view:

has_error = run.status.startswith('error')

Ensure has_error is passed to the template and:

{% if has_error %}

It may be more work, but the logic to detect error conditions could be shared between multiple views and templates, and you separate control logic from view logic.

0đź‘Ť

If you use Django 1.4+ you can use the truncatechars tag but it will only solve partially your answer and will add ellipsis at the end.

The only viable way, a part from concatenating many filters as you already did, is to write a custom filter. Here is a first draft you can customize:

from django import template
from django.template.defaultfilters import stringfilter

register = template.Library()

@register.filter
@stringfilter
def slicestring(value, arg):
    """usage: "mylongstring"|slicestring:"2:4" """
    els = map(int, arg.split(':'))
    return value[els[0]:els[1]]

as a bonus this filter allows you to mimic almost completely the slice notation by providing a “slicing string” as the argument. The only exception seems the syntax [:9] that has to be replaced with [0:9], thus with this argument: yourvariable|slicestring:"0:9"

A side note: Since your question is “getting the first part of a string” I believe a custom filter may be the correct answer, however if the only reason to get a sliced string is to check for a part of it inside an if statement, then I have to agree with Anton: you should place your checks inside the view, not inside the template, when possible.

👤furins

Leave a comment