views:

40

answers:

2

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?

+4  A: 

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.

Ned Batchelder
+1. Makes sense.
Manoj Govindan
1) Yup, that's the way I originally checked for extra characters. There were none.
Sir Conquer
2) I was suspecting that had something to do with it! It is indeed a foreign key reference to instance of shift model! After searching for 2 hours I finally found a way to stringify it!
Sir Conquer
A: 

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

{% if watchinstance.shift|stringformat:"s" == "DAY"  %}
Sir Conquer