【问题标题】:Comparing Django POST data比较 Django POST 数据
【发布时间】:2012-07-16 15:01:52
【问题描述】:

我期待POST 数据,并希望创建一个自定义字典,以便在根据发布的内容创建表单时使用。我似乎在尝试比较 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)

【问题讨论】:

    标签: python django http-post


    【解决方案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())。

    【讨论】:

    • 我喜欢这个解决方案。谢谢。
    【解决方案2】:
     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

    【讨论】:

      猜你喜欢
      • 2023-01-31
      • 2016-08-15
      • 2011-11-11
      • 1970-01-01
      • 1970-01-01
      • 2018-10-08
      • 1970-01-01
      • 2010-10-01
      • 1970-01-01
      相关资源
      最近更新 更多