MaxCore
MaxCore

Reputation: 2738

Django templates - get list of multiple GET param

I have a url with multiple GET params (of the same name) - mycompany.com/?a=1&a=2

When i do in django template:

{{ request.GET }}

I get:

<QueryDict: {'a': ['1', '2']}> 

When i do in django template:

{{ request.GET.a }}

I get:

2

When i try to loop:

{% for a in request.GET.a %}
    {{ a }}
{% endfor %}

I get:

2

How to make behave multiple GET params as list in django templates? Thx!

Upvotes: 5

Views: 2892

Answers (4)

Rich Tier
Rich Tier

Reputation: 9441

{% for name, values in request.GET.lists %}
    {% if name == 'a' %}{{ values|join:", " }}{% endif %}
{% endfor %}

or

{% for name, values in request.GET.lists %}
    {% if name == 'a' %} 
        {% for value in values %}{{ value }}{% endfor %}
    {% endif %}
{% endfor %}

Upvotes: 0

Engensmax
Engensmax

Reputation: 129

A bit wonky, but does the job:

{%for list_of_elements in request.GET.lists%}
    {%for element in list_of_elements.1%}
        {{ element }}
    {%endfor%}
{%endfor%}

Or if you only want a specific list from the query:

{%for list_of_elements in request.GET.lists %}
    {%if list_of_elements.0 == "a"%}
        {%for element in list_of_elements.1%}
            {{ element }}
        {%endfor%}
    {%endif%}
{%endfor%}

Upvotes: 1

MaxCore
MaxCore

Reputation: 2738

Template filter:

[app/templatetags/exampletag.py]

from django import template

register = template.Library()

@register.filter
def get_item(dictionary, key):
    return dict(dictionary).get(key)

Templates:

{% load exampletag %}

{{ request.GET|get_item:'a' }}

How to: Custom template tags and filters

Upvotes: 2

KitKat
KitKat

Reputation: 1515

Template filter:

from django import template

register = template.Library()

@register.filter
def get_list(dictionary, key):
    return dictionary.getlist(key)

Templates:

{% for a in request.GET|get_list:'a' %}
    {{ a }}
{% endfor %}

Upvotes: 10

Related Questions