[Fixed]-Django template variable value to string literal comparison fails

11πŸ‘

βœ…

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.

51πŸ‘

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

Leave a comment