【django学习-07】视图之HttpResponse

  • 前言:视图函数通过return方式返回响应数据,然后生成响应的网页内容呈现在浏览器上。

  • 视图函数主要有两种返回数据的方法

    • HttpResponse:直接返回数据到浏览器上,不能使用模板语言
    • render:页面渲染,可以使用丰富的模板语言
  • 1、render参数介绍

def render(request, template_name, context=None, content_type=None, status=None, using=None):
    """
    Return 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)
  • request:浏览器向服务器发送的请求对象

  • template_name:模板文件名

  • context:模板上下文(模板变量)赋值,以字典格式表示

  • content_type:响应内容的数据格式

  • status:HTTP状态码

  • using:设置模板引擎,用于解析模板文件,生成网页内容

  • 2、locals()

    • 在实际开发过程中,如果视图函数传递的变量过多,在使用context就会显得不合适,而且不利于维护,因此可以使用python内置语法,locals()代替context。
#views.py
def upload(req):
    name = "xwl"
    return render(req,"upload.html",locals())

#upload.py
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>{{ name }}</h1>
</body>
</html>
  • 3、页面跳转:redirect("路径")
    • 案例:登录成功后,跳转到首页
#blog/urls.py
from django.urls import path,re_path,include
from blog import views

urlpatterns = [
    re_path('login',views.login,name="xwl"),
    re_path('home',views.home),
]

#views.py
def login(req):
    if req.method == "POST":
        username = req.POST.get("username")
        pwd = req.POST.get("pwd")
        if username == "xwl" and pwd == "123":
            # return render(req,"home.html",{"name":username})   #跳转到home首页,但是路径没有更改,每次都需要进入home页重新登录
            return redirect("/blog/home")   #跳转到home首页,但是路径有更改,重新进入home页不需要重新登录

    return render(req,"login.html")

def home(req):
    name = "xwl"   #实际场景从数据库获取
    return render(req,"home.html",locals())

#home.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>欢迎{{ name }}登录</h1>
</body>
</html>

#login.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{#<form action="/login" method="post">#}
<form action="{% url "xwl" %}" method="post">
{#    使用别名#}
    <input type="text" name="username">
    <input type="password" name="pwd">
    <input type="submit" value="submit">
</form>

</body>
</html>
  • 总结:render和redirect的区别:
    • 1 if render的页面需要模板语言渲染,需要的将数据库的数据加载到html,那么所有的这一部分,除了写在home的视图函数中,必须还要写在login中,代码重复,没有解耦。
    • 重点: url没有跳转到/home/,而是还在/login/,所以当刷新后又得重新登录。
posted @ 2022-09-01 23:28  Tony_xiao  阅读(151)  评论(0编辑  收藏  举报