django学习~第四篇

django表单
   1  今天继续来学学django的表单
       首先介绍下http的方法,这是最基本的
       GET 方法 GET一般用于获取/查询 资源信息,以?分割URL和传输数据,多个参数用&连接,login.action?name=hyddd&password=idontknow&verify=%E4%BD%A0 %E5%A5%BD GET提交的数据会在地址栏中显示出来
       POST 方法 而POST一般用于更新 资源信息 把提交的数据放置在是HTTP包的包体中 提交的数据不会在地址栏中显示出来

       GET 方法
        # -*- coding: utf-8 -*-

        from django.http import HttpResponse
        from django.shortcuts import render_to_response

        # 表单
        def search_form(request):
        return render_to_response('search_form.html')///重定向到某个页面

       # 接收请求数据
       def search(request):
         request.encoding='utf-8'
         if 'q' in request.GET://获取request字典的键
         message = '你搜索的内容为: ' + request.GET['q']//这里的q为表单的name
       else:
        message = '你提交了空表单'
       return HttpResponse(message)

       request为一个字典,包含着返回的集合
       return HttpResponse 返回变量
       return render_to_response 返回页面
      添加页面
     <!DOCTYPE html>
      <html>
      <head>
      <meta charset="utf-8">
      <title>菜鸟教程(runoob.com)</title>
      </head>
       <body> //这里采用了form表单形式 method为get
       <form action="/search" method="get">
        <input type="text" name="q">
        <input type="submit" value="搜索">
        </form>
        </body>
  </html>
    修改url
    url(r'^search-form$', search.search_form),
    url(r'^search$', search.search),
    经典错误 scii’ codec can’t decode byte 0xef in position 0:ordinal not in range(128)
    我这里遇到的就是django后端函数返回到前端的汉字问题,暂时先去掉
    POST方法
   添加html
   <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>菜鸟教程(runoob.com)</title>
    </head>
    <body>
    <form action="/search-post" method="post">
    {% csrf_token %}
    <input type="text" name="q">
    <input type="submit" value="Submit">
     </form>

     <p>{{ rlt }}</p>
     </body>
      </html>
      添加函数

      from django.shortcuts import render
      from django.views.decorators import csrf

      # 接收POST请求数据
       def search_post(request):
      ctx ={}
      if request.POST:
      ctx['rlt'] = request.POST['q']//这里是POST方法
      return render(request, "post.html", ctx)
      Http Request 主要对象
     1 path
     2 method GET POST Request (G P的集合)方法
     3 COOKIES
     4 FILES
     5 META HTTP头部
     6 session
      在以上两段代码中,均调用了request对象获取值

猜你喜欢

转载自www.cnblogs.com/danhuangpai/p/9140470.html