zoukankan      html  css  js  c++  java
  • django搭建web (五) views.py

    http请求: HttpRequest
    http响应: HttpResponse

    所在位置:django.http

    isinstance(request,HttpResponse) True->request的类型就是HttpRequest

    HttpRequest对象属性:

    Attribute Description
    path 请求页面的全路径
    method ```请求中使用的HTTP方法的字符串表示。全大写表示。例如

           if quest.method == 'GET':
    do_something()
    elif request.method == 'POST': 
    do_something_else() ```
    |GET |包含所有HTTP GET参数的类字典对象 |
    |POST |包含所有HTTP POST参数的类字典对象 |

        localhost:8000/hello/?name=12345
    

    参数名为name,在接收的时候可以如下

        def hello(request):
            print(quest.GET.get('name'))
    
    get() 如果key对应多个value,get()返回最后一个value

    form-表单

    response = HttpResponse("Here is the text of the web page",mimetype="text/plain")
    return response
    
    #等价
    return render(request,'table.html',{'foo':'bar'})
    
    t = loader.get_template('table.html')
    c = {'foo':'bar'}
    return HttpResponse(t.render(c,request),content_type="text/html")
    
    from django.shortcuts import render_to_response
    return render_to_response('table.html',{'foo':'bar'})
    

    redirect 页面跳转

    from django.shortcuts import redirect
    ... ...
    return redirect('http://www.baidu.com')
    

    locals()

    #locals()将当前作用于的变量全部传递给模板变量
    return render_to response('table.html',locals())
    

    demo

    # -*- coding: utf-8 -*-
    from __future__ import unicode_literals
    
    from django.shortcuts import render
    from .models import myQuestion,myAnswer
    # Create your views here.
    
    
    def research(request):
        question_list = myQuestion.objects.all() 
        answer_list = myAnswer.objects.all()
        context = {'question_list':question_list,'answer_list':answer_list}
        return render(request,"polls/index.html",context)
    
    

    在该demo中

    首先从models中引入模型myQuestion,myAnswer

    from .models import myQuestion,myAnswer
    

    其次定义了一个函数hello,这个地方的hello名称要与urls.py中名称对应,例如hello出现在urls.py如下:

    urlpatterns = [
        url(r'^$',views.hello,name = 'hello'),
    ]
    

    之后调用

    question_list = myQuestion.objects.all() 
    

    函数,将myQuestion模型的全部变量以列表形式赋值给question_list,下句类似

    然后

    context = {'question_list':question_list,'answer_list':answer_list}
    

    将列表转成字典,并起上名称,一同赋值给context

    最后

    return render(request,"polls/index.html",context)
    

    将内容context放进templates/polls/index.html文件中渲染,显示

  • 相关阅读:
    windows 系列机器查看tcp 配置
    test windows live writer
    win7 mysql 启动 问题
    用enum枚举量做下标初始化数组
    二层VXLAN静态配置
    pip install scrapy报错原文
    python练习2
    pycharm字体大小设置快捷键的方法
    python练习1
    centos 7下修改IP地址为静态
  • 原文地址:https://www.cnblogs.com/maskerk/p/7699926.html
Copyright © 2011-2022 走看看