How to get a GET request values' list in Django?
Asked Answered
I

5

23

I've an endpoint:

http://127.0.0.1:8000/auction/?status=['omn','aad']

I need to get the status list, hence I do the following

print(request.GET.getlist('status'))
```

It returns me:

```lang-none
[u"['omn','aad']"]
```

which is a list of string of list.

I then use ast.literal_eval to convert string of list to list. Is there a direct method to get the list of status?
Ingles answered 7/5, 2015 at 16:28 Comment(0)
E
54

Don't send it in that format in the first place. The standard way of sending multiple values for a single HTML is to send the parameter multiple times:

http://127.0.0.1:8000/auction/?status=omn&status=aad

which will correctly give you ['omn','aad'] when you use request.GET.getlist('status').

Exactitude answered 7/5, 2015 at 17:24 Comment(2)
Although this is technically correct, it is slightly difficult to work with javascript as many libraries like an object of params. Objects can not have multiple keys and usually be sent across to Django as /auction/?status[]=omn&status[]=aad, so you'd then need to access the key values as request.GET.getlist('status[]').Bingle
The javascript package query-string can help with that (npmjs.com/package/query-string): queryString.parse('foo[]=1&foo[]=2&foo[]=3', {arrayFormat: 'bracket'});Flanna
B
6

Expanding on @DanielRoseman's answer.

The correct way would be to pass each variable as described: http://127.0.0.1:8000/auction/?status=omn&status=aad.

However, if you're using modern Javascript frameworks (Vue, Angular, React) there's a good chance you're passing params as an object (e.g., if you're working with axios, VueResource, etc). So, this is the work around:

Front-end:

let params = {
   status: ['omn', 'aad',]
}

return new Promise((resolve, reject) => {
  axios.get(`/auction/`, { params: params }, }).then(response => {
      resolve(response.data);
  }).catch(error => {
      resolve(error.response);
  });
});

This will then dispatch to Django as the following URL:

[05/Aug/2019 10:04:42] "GET /auction/?status[]=omn&status[]=aad HTTP/1.1" 200 2418

Which can then be picked up in the corresponding view as:

# Before constructing **parameters, it may neccessary to filter out any supurfluous key, value pair that do not correspond to model attributes:
parameters['status__in'] = request.GET.getlist('status[]')

# Using parameters constructed above, filter the Auctions for given status:
auctions = Auction.objects.filter(is_active=True)

auctions = auctions.filter(**parameters)
Bingle answered 5/8, 2019 at 10:11 Comment(0)
C
4

request.GET['status'] would return you ['omn', 'aad'].

Congratulant answered 7/5, 2015 at 16:40 Comment(2)
Worked. Thanks a bunch. However, this would fail if I dont have status in query parameters. Is there a way similar to get method in dictionary, such dictionary.get('key') or None. Can I use similar kind of notation while getting the query parameters? Dont want to use try-except.Ingles
If you use it this way, you will have a str object with "['omn', 'aad']". If you want a list object, see the answer of Daniel Roseman.Selene
R
1

For example, if you access the url below:

https://example.com/?fruits=apple&fruits=orange

Then, you can get the GET request values' list in views.py as shown below. *My answer explains how to get a POST request values' list in Django and my answer explains how to get GET request values in Django:

# "views.py"

from django.shortcuts import render

def index(request):

    print(request.GET.getlist('fruits')) # ['apple', 'orange']
    print(request.GET.getlist('meat')) # []
    print(request.GET.getlist('meat', "Doesn't exist")) # Doesn't exist
    print(request.GET._getlist('fruits')) # ['apple', 'orange']
    print(request.GET._getlist('meat')) # []
    print(request.GET._getlist('meat', "Doesn't exist")) # Doesn't exist
    print(list(request.GET.lists())) # [('fruits', ['apple', 'orange'])]
    print(dict(request.GET)) # {'fruits': ['apple', 'orange']}
    print(request.META['QUERY_STRING']) # fruits=apple&fruits=orange
    print(request.META.get('QUERY_STRING')) # fruits=apple&fruits=orange

    return render(request, 'index.html')

Then, you can get the GET request values' list in index.html as shown below:

{# "index.html" #}

{{ request.META.QUERY_STRING }} {# fruits=apple&fruits=orange #}

In addition, if you access the url below:

https://example.com/?fruits=apple,orange

Then, you can get the GET request values' list in views.py as shown below:

# "views.py"

from django.shortcuts import render

def index(request):

    print(request.GET['fruits'].split(',')) # ['apple', 'orange']
    print(request.GET.getlist('fruits')[0].split(',')) # ['apple', 'orange']
    print(request.GET._getlist('fruits')[0].split(',')) # ['apple', 'orange']
    print(list(request.GET.values())[0].split(',')) # ['apple', 'orange']
    print(list(request.GET.items())[0][1].split(',')) # ['apple', 'orange']
    print(list(request.GET.lists())[0][1][0].split(',')) # ['apple', 'orange']
    print(request.GET.dict()['fruits'].split(',')) # ['apple', 'orange']
    print(dict(request.GET)['fruits'][0].split(',')) # ['apple', 'orange']
    print(request.META['QUERY_STRING']) # fruits=apple,orange
    print(request.META.get('QUERY_STRING')) # fruits=apple,orange

    return render(request, 'index.html')

Then, you can get the GET request values' list in index.html as shown below:

{# "index.html" #}

{{ request.GET.fruits }} {# apple,orange #}
{{ request.GET.dict }} {# {'fruits': 'apple,orange'} #}
{{ request.META.QUERY_STRING }} {# fruits=apple,orange #}
Registered answered 18/9, 2023 at 19:0 Comment(0)
A
-4

Here is the documentation of HTTPRequest and HTTPResponse

Request Response Objects

Aculeate answered 6/8, 2019 at 6:54 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.