[Django]-How to get all GET request values in Django?

5πŸ‘

βœ…

The second parameter is 5, so you access 'Happy birthday':

request.GET.get('5', '')

note that the strings here will contain the single quotes ('…') as content of the string. So normally this should be done without quotes.

You can get a list of key-value pairs with:

>>> dict(request.GET)
{'1': ["'12-18'"], '5': ["'Happy birthday'"]}

This will use the keys as keys of the dictionary, and maps to a list of values, since a single key can occurs multiple times in the querystring, and thus map to multiple values.

1πŸ‘

For example, if you access the url below:

https://example.com/?fruits=apple&meat=beef

Then, you can get all the parameters in views.py as shown below. *My answer explains how to get GET request values in Django:

# "views.py"

from django.shortcuts import render

def index(request):

    print(list(request.GET.items())) # [('fruits', 'apple'), ('meat', 'beef')]
    print(list(request.GET.lists())) # [('fruits', ['apple']), ('meat', ['beef'])]
    print(request.GET.dict()) # {'fruits': 'apple', 'meat': 'beef'}
    print(dict(request.GET)) # {'fruits': ['apple'], 'meat': ['beef']}
    print(request.META['QUERY_STRING']) # fruits=apple&meat=beef
    print(request.META.get('QUERY_STRING')) # fruits=apple&meat=beef

    return render(request, 'index.html')

Then, you can get all the parameters in index.html as shown below:

{# "index.html" #}

{{ request.GET.dict }} {# {'fruits': 'apple', 'meat': 'beef'} #}
{{ request.META.QUERY_STRING }} {# fruits=apple&meat=beef #}

Leave a comment