views.py的文件中。

 

视图函数:
    一定包含两个对象:
        requset---->用户请求相关的所有信息(对象)
        Httpresponse---->响应字符串

一个简单的视图

下面是一个返回当前日期和时间作为HTML文档的视图:

from django.http import HttpResponse
import datetime

def current_datetime(request):
    now = datetime.datetime.now()
    html = "<html><body>It is now %s.</body></html>" % now
    return HttpResponse(html)

让我们逐行阅读上面的代码:

  • datetime库。

  • request

    current_datetime,是因为这个名称能够精确地反映出它的功能。

  • HttpResponse对象。

Django - - - -视图层之视图函数(views)

 

视图函数,围绕着两个对象进行:HttpResponse和HttpRequest

1.HttpRequest

  request---->请求信息

 

属性:

request.path       # 获取访问文件路径

request.method属性   #获取请求中使用的HTTP方式(POST/GET)

request.body      #含所有请求体信息 是bytes类型
request.GET       #GET请求的数据(类字典对象) 请求头中的url中?后面拿值
request.POST     # POST请求的数据(类字典对象) 请求体里拿值

request.COOKIES     #包含所有cookies的标准Python字典对象;keys和values都是字符串。

request.FILES      包含所有上传文件的类字典对象;FILES中的每一个Key都是<input type="file" name="" />标签中
                 name属性的值,FILES中的每一个value同时也是一个标准的python字典对象,包含下面三个Keys:

                 filename:      上传文件名,用字符串表示
                 content_type:   上传文件的Content Type
                 content:       上传文件的原始内容


request.user:       是一个django.contrib.auth.models.User对象,代表当前登陆的用户。如果访问用户当前
                 没有登陆,user将被初始化为django.contrib.auth.models.AnonymousUser的实例。你
                 可以通过user的is_authenticated()方法来辨别用户是否登陆:
                 if req.user.is_authenticated();只有激活Django中的AuthenticationMiddleware
                 时该属性才可用

request.session      唯一可读写的属性,代表当前会话的字典对象;自己有激活Django中的session支持时该属性才可用

request.GET.get('name')    拿到GET请求里name的值

如果某个键对应有多个值,则不能直接用get取值,需要用getlist,如:

request.POST.getlist("hobby")


请求url:http://127.0.0.1:8000/index.html/23?a=1

request.path : 请求路径      
       request.path结果为:/index.html/23

request.get_full_path()
       request.get_full_path()结果为:/index.html/23?a=1

 

方法:

1
get_full_path()

注意:键值对的值是多个的时候,比如checkbox类型的input标签,select标签,需要用:

1
request.POST.getlist("hobby")

 

2.HttpResponse

  HttpResponse---->相应字符串

  对于HttpRequest请求对象来说,是由django自动创建的,但是,HttpResponse响应对象就必须我们自己创建。每个view请求处理方法必须返回一个HttpResponse响应对象。HttpResponse类在django.http.HttpResponse。

在HttpResponse对象上扩展的常用方法

 1.render 函数

  将指定页面渲染后返回给浏览器

render(request, template_name[, context])

结合一个给定的模板和一个给定的上下文字典,并返回一个渲染后的 HttpResponse 对象。

参数:
     request: 用于生成响应的请求对象。

     template_name:要使用的模板的完整名称,可选的参数

     context:添加到模板上下文的一个字典。默认是一个空字典。如果字典中的某个值是可调用的,视图将在渲染模板之前调用它。

     content_type:生成的文档要使用的MIME类型。默认为DEFAULT_CONTENT_TYPE 设置的值。

     status:响应的状态码。默认为200。
from django.shortcuts import render

def test(request):
    return render(request,'index.html')   #向用户显示一个html页面

下面为render官方源码,可以看出render最后也是返回了一个HttpResponse给webserver

def render(request, template_name, context=None, content_type=None, status=None, using=None):
    """
    Returns a HttpResponse whose content is filled with the result of calling
    django.template.loader.render_to_string() with the passed arguments.
    """
    content = loader.render_to_string(template_name, context, request, using=using)
    return HttpResponse(content, content_type, status)

细说render:

  render方法主要是将从服务器提取的数据,填充到模板中,然后将渲染后的html静态文件返回给浏览器。这里一定要注意:render渲染的是模板,下面我们看看什么叫作模板:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
    <style>
        li,ul,ol{  list-style: none;  }
        a{ text-decoration: none; }
    </style>
</head>
<body>
<ul>
    {% for book in list %}
        <li><a href="{{book.id}}">{{ book.btitle }}</a></li>
    {% endfor %}
</ul>
</body>
</html>

 

上面{%%}之间包括的就是我们要从数据库取出的数据,进行填充。对于这样一个没有填充数据的html文件,浏览器是不能进行渲染的,所以,对于上述{%%}之间的内容先要被render进行渲染之后,才能发送给浏览器。

  下面举个例子:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
    <style>
        li,ul,ol{  list-style: none;  }
        a{ text-decoration: none; }
    </style>
</head>
<body>
<ul>
    {% for book in list %}
        <li><a href="{{book.id}}">{{ book.btitle }}</a></li>
    {% endfor %}

</ul>
</body>
</html>
show.html

相关文章: