Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django template variable value to string literal comparison fails

I have the following code in my template that supposed to compare the value of watchinstance.shift, which can be either "DAY" or "NIGHT", to a literal string "DAY". The comparisson always fails.

{% for watchinstance in watchinstance_list %}
    {% if watchinstance.shift == "DAY" %}
        <p>shift is DAY</p>
    {% endif %}
{% endfor %}

Using ifequal doesn't work either:

{% for watchinstance in watchinstance_list %}
    {% ifequal watchinstance.shift "DAY" %}
        <p>shift is DAY</p>
    {% endifequal %}
{% endfor %}

However, just calling {{ watchinstance.shift }} works as expected:

{% for watchinstance in watchinstance_list %}
    {{ watchinstance.shift }}
{% endfor %}

returns DAYs and NIGHTs.

I checked whether watchinstance.shift returns any extra characters, and it doesn't look like it does... What else can I be missing here?

like image 878
Sir Conquer Avatar asked Sep 17 '10 01:09

Sir Conquer


People also ask

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

Which characters are illegal in template variable names in Django?

Variable names consist of any combination of alphanumeric characters and the underscore ( "_" ) but may not start with an underscore, and may not be a number.

What is Forloop counter in Django?

A for loop is used for iterating over a sequence, like looping over items in an array, a list, or a dictionary.

What does the built in Django template filter safe do?

This flag tells Django that if a “safe” string is passed into your filter, the result will still be “safe” and if a non-safe string is passed in, Django will automatically escape it, if necessary. You can think of this as meaning “this filter is safe – it doesn't introduce any possibility of unsafe HTML.”


2 Answers

So after searching Django docs for 2 hours, I finally found a way to make it work:

{% if watchinstance.shift|stringformat:"s" == "DAY"  %}
like image 114
Sir Conquer Avatar answered Oct 15 '22 00:10

Sir Conquer


A couple of possibilities:

  1. The .shift string has extra whitespace. Use this to double-check:

    {% for watchinstance in watchinstance_list %}
        X{{ watchinstance.shift }}X
    {% endfor %}
    
  2. The .shift attribute isn't a string, but an object that stringifies to "DAY" or "NIGHT". In that case, the variable substitution in {{ watchinstance.shift }} would look the same as a string, but the comparison in {% ifequal watchinstance.shift "DAY" %} would fail.

like image 22
Ned Batchelder Avatar answered Oct 14 '22 23:10

Ned Batchelder