Finding 2 values if available in a list in a Django Template

Question:

I have the following list called “ :[(2, 'Flat Bench'), (1, 'Flat Bench'), (3, 'Flat Bench')]

I am trying to find if the b.order which is the first number and e.name which is the 2nd string is available from a django template. In my trial I made sure that b.order is equal to 2 and e.name is ‘Flat Bench’.

Here is the django template:

  {% if b.order and e.name in all_logs %}
  available
  {% else%}
  not available
  {% endif %}

In my case there is no error, it is just always showing not available even if it is available.

I am not sure what change I should be doing to get this code to work.

Asked By: A_K

||

Answers:

Try the following:

{% if b.order in all_logs and e.name in all_logs %}
  available
  {% else%}
  not available
{% endif %}

This way, it checks each if each item is in the list separately. If they both are, (no matter if index differs) it will show available.

Answered By: nigel239

Well, I would suggest to create custom tags as explained here: https://docs.djangoproject.com/en/4.1/howto/custom-template-tags/

Your custom function should look as follows:

my_custom_tags.py

from django import template

register = template.Library()


@register.simple_tag
def tuple_check(items, key, value):
    return (key, value) in items

Your template should have the following:

{% load my_custom_tags %}
...
some codes here
...

{% tuple_check your_list b.order e.name as item_check_result %}

{% if item_check_result %}
Available
{% else %}
Not Available
{% endif %}
Answered By: Abdullah