charset model aps mode val 响应 def hid
views 视图围绕两个对象实现的。
逻辑处理函数的第一个形式参数,接收到的就是 HttpRequest 对象,这个对象里封装着用户的各种请求信息,通过 HttpRequest 对象的方法或者属性,可以获取到响应的请求信息.
1. 属性
- request.path#获取访问文件路径
- request.method属性#获取请求中使用的HTTP方式(POST / GET)
- request.GET#获取HTTP GET方式请求传参(字典类型)
- request.POST#包含所有HTTP POST参数的类字典对象
- request.COOKIES#包含所有cookies的标准Python字典对象;keys和values都是字符串。
- request.FILES#包含所有上传文件的类字典对象
- request.user#是一个django.contrib.auth.models.User对象,代表当前登陆的用户
- request.session#唯一可读写的属性,代表当前会话的字典对象
2. 实例
- from django.shortcuts import render,HttpResponse
- def special(request):
- print(request.path)
- print(requst.method)
- return render(request,'index.html')
对于 HttpRequest 请求对象来说,是由 django 自动创建的,但是,HttpResponse 响应对象就必须我们自己创建。每个 view 请求处理方法必须返回一个 HttpResponse 响应对象。
HttpResponse 类在 django.http.HttpResponse
1. 在 HttpResponse 对象上扩展的常用方法
render(请求对象,'html 文件和路径') 方法,将指定页面渲染后返回给浏览器
- from django.shortcuts import render
- def test(request):
- return render(request,'index.html') #向用户显示一个html页面
render_to_response('html 文件和路径') 方法,将指定页面渲染后返回给浏览器
- from django.shortcuts import render
- def test(request):
- return render_to_reponse(request,'index.html') #向用户显示一个html页面
redirect('跳转路径和名称') 方法,页面跳转
- from django.shortcuts import render,render_to_response,redirect
- def test(request):
- return redirect('http://www.jxiou.com/') #跳转页面
locals(变量名称) 可以直接将逻辑处理函数中的所有变量传给模板
- from django.shortcuts import render
- def test(request):
- a = 123
- b = 456
- c = 789
- return render(request,'index.html',locals()) #跳转页面
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Title</title>
- </head>
- <body>
- <h1>主页</h1>
- <p>{{ a }}</p>
- <p>{{ b }}</p>
- <p>{{ c }}</p>
- </body>
- </html>
Django - 再谈 views 视图
来源: http://www.bubuko.com/infodetail-2270448.html