Python Django请求获取参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4162625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:33:28  来源:igfitidea点击:

Django request get parameters

pythondjangodjango-modelsdjango-views

提问by Hulk

In a Django request I have the following:

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

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

How do I get the values of sectionand MAINS?

我如何获得的价值sectionMAINS

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

section_id = qd.__getitem__('section') or getlist....

采纳答案by Johannes Gorset

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

您可以像使用任何普通字典一样[]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]

回答by crodjer

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

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