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 ""
    
  • 相关阅读:
    View转化为bitmap
    Bitmap 与Drawable相互转换
    android studio 连接不到真机
    解决Android sync无法同步问题
    Stetho管理手机
    android sugar no such table
    android 建数据库的正确写法
    android JSON 数据解析
    android notification 理解
    android aidl 简单使用
  • 原文地址:https://www.cnblogs.com/ccorz/p/6346883.html
Copyright © 2011-2022 走看看