Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django get first part of a string

Tags:

python

django

Is there a simple django tag to get the first x characters of a string in a template?

In a list of modelinstances, I would like to give a different symbol per objectinstance, depending on the status of the objectinstance. Status could be 'waiting', 'success' or 'failed XXXX', with XXXX being the errorcode.

I would like to check if the first 5 characters of objectinstance.status == 'error', then the symbol will be red. However, how can I do this? In Python I could use objectinstance.status[:5].

Using https://docs.djangoproject.com/en/dev/ref/templates/builtins/ I managed to do this with following 'monstruous' concatenation, but is there something simple as .left() or .right()?

{% if run.status|make_list|slice:":5"|join:"" == 'error' %}
like image 819
Bart P. Avatar asked Dec 11 '25 09:12

Bart P.


1 Answers

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.

like image 73
Anton I. Sipos Avatar answered Dec 13 '25 22:12

Anton I. Sipos