Python code in html is not working properly

Asked

Viewed 44 times

0

I’m using Python and Django for a web application, at a certain point I make the following code in the html:

{% for oportunidade in all_oportunidades %}
    <a>{{oportunidade.categoria}}</a>
    <br>
    {% if oportunidade.categoria == 1 %}
        <a>teste</a>
        <br>
    {%endif%}
{% endfor %}
    {% endfor %}

The result I’m getting is this::

None
2
0
1
1
2
None

But the result I hope for is this::

None
2
0
1
teste
1
teste
2
None

What I’m doing wrong?

  • 1

    Try to do so if opportunity.category == '1'

  • 1

    Or try this way if int(opportunity.category) == 1

  • It worked with simple quotes, thank you!

1 answer

1


Solutions

Comparing strings

Its variable categoria is not an integer, so you need to make the comparison using quotes, passing the representation to string, as in this example.

{% for oportunidade in all_oportunidades %}
    <a>{{oportunidade.categoria}}</a>
    <br>
    {% if oportunidade.categoria == "1" %}
        <a>teste</a>
        <br>
    {%endif%}
{% endfor %}

Comparing integers

Or, you can convert your variable to integer as follows.

{% for oportunidade in all_oportunidades %}
    <a>{{oportunidade.categoria}}</a>
    <br>
    {% if int(oportunidade.categoria) == 1 %}
        <a>teste</a>
        <br>
    {%endif%}
{% endfor %}

Best method

My opinion

I believe that the best solution to your problem is to convert the value to integer, since there is the possibility of a comparison with an integer value, that is, let’s assume that at a certain time the value of "category" is 1 but of the integer type, it will not show the <a>teste</a><br>.

Testing

Test 1

valor = 1

if valor == '1':
  print("primeiro")

if valor == 1:
  print("segundo")

Upshot

according to

Execute

Test 2

valor = "1"

if valor == "1":
  print("primeiro")

if valor == 1:
  print("segundo")

Upshot

first

Execute

Test 3

valor = "1"

if int(valor) == 1:
  print("primeiro")

if str(valor) == "1":
  print("segundo")

Upshot

first
according to

Execute

Test 4

valor = 1

if int(valor) == 1:
  print("primeiro")

if str(valor) == "1":
  print("segundo")

Upshot

first
according to

Execute

Completion

It is always good to know the type of the variable before making a comparison, especially in language that is not "typed" as is the case with python, but if your problem does not allow to have a prediction of what will be the type, it is good to do the conversion, so even if you receive an unexpected type in the conversion this will be solved, as in test 3 and 4.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.