Django request get parameters

Hulk picture Hulk · Nov 12, 2010 · Viewed 130.8k times · Source

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....

Answer

crodjer picture crodjer · Nov 12, 2010

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).