Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django request get parameters

In a Django request I have the following:

POST:<QueryDict: {u'section': [u'39'], u'MAINS': [u'137']}> 

How do I get the values of section and MAINS?

if request.method == 'GET':     qd = request.GET elif request.method == 'POST':     qd = request.POST  section_id = qd.__getitem__('section') or getlist.... 
like image 720
Hulk Avatar asked Nov 12 '10 07:11

Hulk


People also ask

How do I get all query parameters in Django?

We can access the query params from the request in Django from the GET attribute of the request. To get the first or only value in a parameter simply use the get() method. To get the list of all values in a parameter use getlist() method.


2 Answers

You may also use:

request.POST.get('section','') # => [39] request.POST.get('MAINS','') # => [137]  request.GET.get('section','') # => [39] request.GET.get('MAINS','') # => [137] 

Using this ensures that you don't get an error. If the POST/GET data with any key is not defined then instead of raising an exception the fallback value (second argument of .get() will be used).

like image 195
crodjer Avatar answered Sep 22 '22 05:09

crodjer


You can use [] to extract values from a QueryDict object like you would any ordinary dictionary.

# HTTP POST variables request.POST['section'] # => [39] request.POST['MAINS'] # => [137]  # HTTP GET variables request.GET['section'] # => [39] request.GET['MAINS'] # => [137]  # HTTP POST and HTTP GET variables (Deprecated since Django 1.7) request.REQUEST['section'] # => [39] request.REQUEST['MAINS'] # => [137] 
like image 43
Johannes Gorset Avatar answered Sep 21 '22 05:09

Johannes Gorset