0

I have array, lets say it:

str_types = ("open", "closed", "extend", "cancel")

Also I've some table. Which have int field named "type", contains number from 1 - 4. If field value is 1, It must print "open", if value equals 2, I must print "closed" etc.

So in template:

{% for a in ticket %}
<div>{{ str_types.a.types }}</div>
{% endfor %}

Result is blank. How to access that str_types array's index?

1 Answer 1

2

You can't do it without custom template tag or filter.

from django import template

register = template.Library()

@register.filter
def get_by_index(l, i):
    return l[i]

And the in the template:

{% load my_tags %}
{{ str_types|get_by_index:a.types }}

But why you need this? The django way is to set the choices attribute of the types field and the use it in the template as {{ a.get_types_display }}.

Sign up to request clarification or add additional context in comments.

6 Comments

I don't have model. I just reading from existed database, using raw sql.
Then you have to add the field in the view (simple) or use the template filter (more complicated). I added the example of such filter to the answer.
Never created custom filter before. I'll try and report back.
I just created templatetags folder in my app. Then created _init_.py empty file. Then created custom_filters.py. And put your codes inside it. Then loaded it in template {% load custom_filters %}. Then when I try use filter, error happening. 'custom_filters' is not a valid tag library: Template library custom_filters not found
Just restarted my service. And it works :) Thank you much sir.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.