intelis
intelis

Reputation: 8068

Dynamically access request.GET in Django template

I'm trying to dynamically access GET parameters in Django template, but it's not working.

URL: ?id=1&name=John

I've tried something like this:

{% for r in request.GET %}
    {% if request.GET.r %}
        {{r}} = {{request.GET.r}}
    {% endif %}
{% endfor %}

The problem is that even if the parameters are set, nothing is returned in the template.

It works though if I do request.GET.id or request.GET.name

Any ideas?

Upvotes: 5

Views: 8227

Answers (2)

Engensmax
Engensmax

Reputation: 129

I had the same problem, but with the additional challenge of having multiple values with the same key.

URL: ?id=1&id=2&id=3&id=4

In that case i used the following:

{%for key, values in request.GET.lists%}
    {%for value in values%}
        {{value}}  
    {%endfor%}
{%endfor%}

Upvotes: 1

ilse2005
ilse2005

Reputation: 11439

As request.GET is a dictionary, you should use request.GET.items in the loop (docs).

{% for key, value in request.GET.items %}
    {{key}} = {{value}}
{% endfor %}

Upvotes: 13

Related Questions