比较Django POST数据



我需要POST数据,并希望创建一个自定义字典,以便在基于POSTed创建表单时使用。我似乎在尝试比较POST数据中的内容时遇到了问题。我在Ubuntu 12.04上使用Django 1.4和Python 2.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,
                }

这不起作用。我正在用get填充字段,两个字典都没有创建。

你建议我做什么?

编辑:我的问题似乎是我的更改没有在Django服务器上更新。(必须重新启动Apache)

以下是我将如何处理它。

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也不是post

最新更新