zoukankan      html  css  js  c++  java
  • django中同通过getlist() 接收页面form的post数组

    前端中的一些东西:

    <form action="people?action=edit" method="post">
      <input type="text" name="peoName"/>
      <input type="text" name="peoName"/>
      <input type="text" name="peoName"/>
    </form>
    

    在后台处理中可以通过以下代码获取参数:

    peoNames = request.POST.getlist('peoName',[])
    

    获取到的peoNames是一个数组,遍历就可以得到所有元素的值,注意,request.POST的类型是QueryDict,和普通的Dict不同的是,如果使用request.POST.get方法,只能获得数组的最后一个元素,必须使用getlist才能获取整个数组,以Python列表的形式返回所请求键的数据。 若键不存在则返回空列表。 它保证了一定会返回某种形式的list。

    看下面的例子:


    若用户输入了 "John Smith" 在 your_name 框并且选择在多选框中同时选中了 The Beatles 和 The Zombies, 然后点击 Submit, Django的request对象将拥有:

    >>> request.GET
    {}
    >>> request.POST
    {'your_name': ['John Smith'], 'bands': ['beatles', 'zombies']}
    >>> request.POST['your_name']
    'John Smith'
    >>> request.POST['bands']
    'zombies'
    >>> request.POST.getlist('bands')
    ['beatles', 'zombies']
    >>> request.POST.get('your_name', 'Adrian')
    'John Smith'
    >>> request.POST.get('nonexistent_field', 'Nowhere Man')
    'Nowhere Man'
    

    关于django的POST常见方法

    1.用post方法去取form表单的值
    
      在取值前,先得判断是否存在这个key
    
      if not request.POST.has_key(strName):
          return "" 
      if request.POST[strName]:
          return request.POST[strName] 
      else:
          return ""
    
    2.用post方法获取[]类型的数据
    
      常见的,例如,每行数据前面都带个checkbox的操作。这时候可能会选多个checkbox,传入到后台时,如果用request.POST[strname]获取,那么只能获取到一个值。用下面的方法,可以获取到多值
    
      if not request.POST.has_key(strName):
          return "" 
      if request.POST[strName]:
          return ','.join(request.POST.getlist(strName)) 
      else:
          return ""
    
  • 相关阅读:
    idea 管理java 多module的工程
    协程与函数线程异步的关系
    HDU 5640 King's Cake【模拟】
    逻辑运算
    Silverlight 学习笔记——布局 Evil 域 博客园
    ExtJS 日期格式问题
    偏方收藏(此信息为本人收藏,安全性无法验证,使用后产生的一些后果自负)
    form和column:extJS的布局
    Sqlserver 通用存储过程分页
    Ext中TreePanel控件和TabPanel控件搭配测试
  • 原文地址:https://www.cnblogs.com/ccorz/p/6346883.html
Copyright © 2011-2022 走看看