0

I have the following array and would like to display day name in the template.

DAYS = ((0, "Saturday"),
        (1, "Sunday"),
        (2, "Monday"),
        (3, "Tuesday"),
        (4, "Wednesday"))

I can display Monday by using {{ DAYS.2.1 }} but I was unable to display using {{DAYS.class_weekday.key_value.1}}.

I am getting class_weekday.key_value from a for loop but when I use class_weekday.key_value there then it's not showing anything!

Thank you!

3 Answers 3

5

You can use

{{ instance.get_day_display }}

in your templates. That select the display value instead of the database value.

If you want to display all the values :

[ x for x, y in DAYS ]

will return a list containing the list of days,

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

2 Comments

Thanks! I am not using for loop in the template. The DAYS array is available in the template but I want to just display the value based on the key i.e. {{ DAYS[2] }} for Monday.
do you know how to use weekday.key_value from a for loop i.e. {{DAYS.weekday.key_value.1}} to display the day name? When I use weekday.key_value there then it's not showing anything! Thanks!
1

As per django

https://docs.djangoproject.com/en/1.10/ref/templates/api/#variables-and-lookups

Variables and lookups

Variable names must consist of any letter (A-Z), any digit (0-9), an underscore (but they must not start with an underscore) or a dot.

Dots have a special meaning in template rendering. A dot in a variable name signifies a lookup. Specifically, when the template system encounters a dot in a variable name, it tries the following lookups, in this order:

Dictionary lookup. Example: foo["bar"]
Attribute lookup. Example: foo.bar
List-index lookup. Example: foo[bar]

Note that “bar” in a template expression like {{ foo.bar }} will be interpreted as a literal string and not using the value of the variable “bar”, if one exists in the template context.

So you can use custom filter for this purpose.

You can make custom template filter:

#here, import DAYS
@register.filter
def return_day(i):
    try:
        return DAYS[i][1]
    except:
        return N.A

And in template

{{ class_weekday.key_value|return_day }}

Comments

-2

What you want is DAYS[2][1] :)

2 Comments

This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review
this clairly respond to the question @stovfl, he just want to display 'Monday', for now he print only a tuple, et need the extra [1], someone else posted the same on a comment and that was the answer...

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.