zoukankan      html  css  js  c++  java
  • 视图函数

    视图函数

    • request 请求视图对象

      def index(request):
          print(request.path)  # 请求路径  /index/
          print(request.GET)  # get方法的请求数据, 字典格式.即浏览器地址栏127.0.0.1/index/?a=1&b=2 参数.<QueryDict: {'a': ['1'], 'b': ['2']}>
          print(request.POST)  # post方法的请求数据, 字典格式
          print(request.META)  # 请求头,字典
          print(request.get_full_path())  # 方法, 包括路径和参数   /index/?a=1&b=2
          print(request.is_ajax())  # 判断是否是ajax发的请求, 此处为浏览器发的请求,并非ajax
          return HttpResponse('sucess')
      
      
    • response 响应

      django 对于请求最后一定响应一个HttpResponse对象

      • render
      • HttpResponse
      • redirect
      1. HttpResponse("字符串"):

        可以是普通字符串,也可以是浏览器能够识别的标签字符串 <h1>xxx</h1>
      2. render("页面"), 语法:render(request, '页面文件', 参数(需要模板渲染的变量, 字典格式))

        render(request, 'index.html', {'name': var}) name: django模板的变量, var:views视图函数中的变量名或字符串

        • 读取页面文件字符串

        • 页面中嵌入变量(重要), 在经过模板渲染,django模板语法:

          • {{ }} -----> 变量渲染
          • {% %} ----> 标签渲染

          html页面中不可能写死商品名称,应从数据库中取出数据,再放入页面,所有要有变量。如

          <body>
          
          <h3>商品信息</h3>
          <p>苹果</p>  # 商品应从数据库中调用
          
          </body>
          
          #views.py
          def index(request):
           shangping = '苹果'
           return render(request, 'index.html', {'sp': shangping})
          
          
          <!DOCTYPE html>
          <html lang="en">
          <head>
           <meta charset="UTF-8">
           <title>Title</title>
          </head>
          
          <body>
          
          <h3>商品信息</h3>
          <p>{{ sp }}</p> #######变量渲染
          
          </body>
          </html>
          
      3. redirect() 重定向

        重定向包含2次请求,第一次请求页面,服务器响应重定向请求,浏览器根据重定向信息地址请求页面,服务器响应页面

        def login(request):
            if request.method == 'GET':
                return render(request, 'login.html')
            elif request.method == 'POST':
                username = request.POST.get('username')
                password = request.POST.get('password')
                if username == 'sunny' and password == '123':
                    return redirect('/index/')  # 重定向包含2次请求,浏览器第一次login页面,服务器响应location:/index/, 浏览器请求/index/, 服务器响应index.html页面
                else:
                    return HttpResponse('Wrong username or password')
        

        重定向POST第一次请求:

        第二次根据location浏览器进行get请求:

  • 相关阅读:
    用JSP实现的商城购物车模块
    C语言中的static 具体分析
    JAVA动态代理
    ACM之跳骚---ShinePans
    thinkphp5项目--个人博客(二)
    mysql数据类型
    htm、html、shtml网页区别
    thinkphp命名空间
    github README.md教程
    如何在github的README.md中添加图片
  • 原文地址:https://www.cnblogs.com/relaxlee/p/12842739.html
Copyright © 2011-2022 走看看