2012-07-16 74 views
0

我期待POST数据,并希望创建一个自定义字典,以创建基于POST的内容时使用的表单。我似乎遇到了一些问题,试图比较POST数据中的内容。我在Ubuntu 12.04上使用Python 2.7的Django 1.4。比较Django的POST数据

假设我有一个名为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)

回答

1

这是我会怎么处理它。

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())。

+0

我喜欢这个解决方案。谢谢。 – Rico 2012-07-16 17:45:28

+0

不客气,Rico。 – 2012-07-16 20:08:44

1
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