【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/,所以当刷新后又得重新登录。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现