比较Django POST d

2024-09-21 00:47:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要POST数据,并希望创建一个自定义字典,以便在基于所发布内容创建表单时使用。我在比较POST数据时似乎遇到了问题。我在Ubuntu12.04上使用Django1.4和Python2.7。在

假设我有一个名为return_methodPOST字段,它将告诉我客户机期望的返回方法的类型。它们将发送值postget。现在,我想根据我得到的值创建不同的字典。在

if (request.POST.get('return_method') == 'get'):
    cust_dict = { 'key1' : value1,
                  'key2' : value2,
                  'key3' : value3,
                }

elif (request.POST.get('return_method') == 'post'):
    cust_dict = { 'key1' : value1,
                  'key2' : value2,
                  'key3' : another_value,
                }

这不管用。{dictionary}和填充字段都没有创建。在

你建议我怎么做?在

编辑:看来我的问题是我的更改没有在Django服务器上更新。(不得不重新启动Apache)


Tags: 数据getreturn字典requestpostmethoddict
2条回答

下面是我将如何处理它。在

custom = {
  "get" : {
    'key1' : value1,
    'key2' : value2,
    'key3' : value3,
  },

  "post" : {
    'key1' : value1,
    'key2' : value2,
    'key3' : another_value,
  },
}

try:
    cust_dict = custom[request.POST.get('return_method').strip()]
except KeyError:
    # .. handle invalid value

也就是说,你的版本没有理由不起作用。你检查过你在request.POST.get('return_method')中看到的值了吗?也许值中有空格阻碍了字符串匹配(注意上面示例代码中的.strip())。在

 cust_dict = { 'key1' : value1,
               'key2' : value2,
             }


if request.POST.get('return_method') == 'get'): 
  cust_dict['key3'] = value3
elif request.POST.get('return_method') == 'post):
  cust_dict['key3'] = another_value

如果key3未添加到cust_dict中,则return_method的值既不是get也不是{}

相关问题 更多 >

    热门问题