Django请求获取参数

Hul*_*ulk 70 python django django-models django-views

在Django请求中,我有以下内容

POST:<QueryDict: {u'section': [u'39'], u'MAINS': [u'137']}>
Run Code Online (Sandbox Code Playgroud)

如何获得的价值sectionMAINS

if request.method == 'GET':
    qd = request.GET
elif request.method == 'POST':
    qd = request.POST

section_id = qd.__getitem__('section') or getlist....
Run Code Online (Sandbox Code Playgroud)

cro*_*jer 175

您也可以使用:

request.POST.get('section','') # => [39]
request.POST.get('MAINS','') # => [137] 
request.GET.get('section','') # => [39]
request.GET.get('MAINS','') # => [137]
Run Code Online (Sandbox Code Playgroud)

使用它可确保您不会收到错误.如果没有定义带有任何键的POST/GET数据,那么将使用回退值(将使用.get()的第二个参数)而不是引发异常.


Joh*_*set 76

您可以像使用任何普通字典一样[]QueryDict对象中提取值.

# 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]
Run Code Online (Sandbox Code Playgroud)

  • 这些年后只是一个提示:request.REQUEST同时被弃用了 (9认同)