0

I have this in my models:

class Task(Record):

    class Status(models.IntegerChoices):
        OPEN = 1, "Open"
        COMPLETED = 2, "Completed"
    status = models.IntegerField(choices=Status.choices, db_index=True, default=1)

Then in my template I want to show all the statuses, so I do this in views.py:

context = { 
  "statuses": Task.Status.choices,
}

And in my template I loop through it:

{% for label,name in statuses %}
  {{ label }}: {{ name }}
{% endfor %}

This leads to:

1: Open
2: Completed

So far, so good. But now if I use a GET parameter, I can't get things to work as I want. Say I open ?id=2 and then I run:

{% for label,name in statuses %}
  {{ label }}: {{ name }} 
  {% if label == request.GET.id %}
     YES
  {% else %} 
     Sorry, not equal to {{ request.GET.id }}
  {% endif %}
{% endfor %}

Then I expect this to show YES for the first item. But it doesn't! Somehow this evaluates to:

1: Open Sorry, not equal to 1 
2: Completed Sorry, not equal to 1

I do not understand why the first item does not evaluate to true.

1 Answers1

0

In your view to store this value into context and pass with template . Get data from request like this

request.GET.get('id')

and make sure data type of both must be same otherwise you will always execute else condition.

Capturing url parameters in request.GET

  • That syntax makes sense in the views.py file, but in this case I'm working in the template and that doesn't work (Could not parse the remainder... error). –  Jun 09 '20 at 16:11
  • OK noted, but does that mean that you can not do these kinds of comparisons directly in the templates? Do you know the reason? –  Jun 10 '20 at 05:26
  • NOTE: I actually had to type cast the request.GET["id"] as integer, only then would it work. –  Jun 10 '20 at 05:30
  • You can do comparison in templates but same data type needed. – Muhammad Faizan Fareed Jun 10 '20 at 06:55