Django-请求参数和响应方式
0x01 请求和响应的方式
def something(request):
# 关于request:是一个对象封装了用户发送过来的所有请求数据
# 获取用户请求方式,GET/POST
print(request.method)
# 获取GET参数
print(request.GET)
# 获取POST参数
print(request.POST)
# 获取GET中的a参数
print(request.GET['a'])
# 响应方式1.通过render方式,通过html模板输出
return render(request,"something.html")
# 响应方式2.通过HttpResponse方式,直接返回内容
return HttpResponse(request.GET['a'])
# 响应方式3.通过redirect方式,重定向链接
return redirect("https://www.baidu.com")
0x02 一个简单的登录界面示例
login.html部分:
这边需要注意一定要在form表单上加一句{% csrf_token %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h1>用户登录</h1>
<form method="post" action="/login/">
{% csrf_token %}
<input type="text" name="user" placeholder="用户名">
<input type="password" name="passwd" placeholder="密码">
<input type="submit" value="提交">
</form>
<span style="color: red"> {{ error_msg }}</span>
</body>
</html>
views.py login方法部分:
def login(request):
if request.method == "GET":
return render(request, "login.html")
elif request.method == "POST":
username = request.POST['user']
password = request.POST['passwd']
if username == "root" and password == "123456":
return HttpResponse("登陆成功")
else:
error_msg = "登录失败,用户名或者密码错误"
return render(request, "login.html", {"error_msg": error_msg})