码迷,mamicode.com
首页 > 其他好文 > 详细

Django-再谈views视图

时间:2017-08-20 18:23:23      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:信息   获取   play   django   rom   ati   名称   包含   http   

views视图围绕两个对象实现的。

一、HttpRequest对象

  逻辑处理函数的第一个形式参数,接收到的就是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)

2.HttpResponse对象

  对于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>
index.html

 

Django-再谈views视图

标签:信息   获取   play   django   rom   ati   名称   包含   http   

原文地址:http://www.cnblogs.com/vipchenwei/p/7400617.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!