目录
2.2 app01/views.py文件里定义好视图函数login
1. 请求和响应
1.1 请求
- 获取请求方式;
- 获取URL传递的值;
- 获取请求体传递的值。
1.2 响应
- 返回字符串;
- 返回html文件;
- 返回重定向。
1.3 实例代码
from django.shortcuts import render, HttpResponse, redirect
def something(request):
# request 是一个对象,封装了用户发送过来的所有请求相关数据
# 1. 获取请求方式 GET/POST
print(request.method)
# 输出:GET
# 2. 在URL上传递值 /something/?n1=123&n2=456
print(request.GET)
# 输出:<QueryDict: {'n1': ['123'], 'n2': ['456']}>
# 3. 在请求提中提交数据
print(request.POST)
# 4.【响应】HttpResponse("返回内容"),内容字符串返回给请求者
# return HttpResponse("请求成功")
# 5.【响应】读取HTML内容 + 渲染(替换) -> 字符串,返回给用户浏览器
# return render(request, "something.html", {"titile": "happy"})
# 6.【响应】让浏览器重定向到其它页面
return redirect("https://www.baidu.com")
2. 案例-用户登录
2.1 mysite/urls.py新增一条路由
urlpatterns = [
# path('admin/', admin.site.urls),
path('login/', views.login),
]
2.2 app01/views.py文件里定义好视图函数login
def login(request):
if request.method == "GET":
return render(request, "login.html")
else:
# 如果是POST请求,获取用户提交的数据
# print(request.POST)
username = request.POST.get("username")
password = request.POST.get("password")
if username == "root" and password == "123":
return HttpResponse("登录成功!")
else:
return render(request, 'login.html', {"error_msg": "用户名或密码错误"})
if...else... 嵌套有点多,对代码进行优化,减少if...else...嵌套:
def login(request):
if request.method == "GET":
return render(request, "login.html")
# 如果是POST请求,获取用户提交的数据
# print(request.POST)
username = request.POST.get("username")
password = request.POST.get("password")
if username == "root" and password == "123":
return HttpResponse("登录成功!")
return render(request, 'login.html', {"error_msg": "用户名或密码错误"})
2.3 编写HTML文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户登录</title>
</head>
<body>
<h2>用户登录</h2>
<form method="post" action="/login/">
<input type="text" name="username" placeholder="用户名">
<input type="password" name="password" placeholder="密码">
<input type="submit" value="提交">
<span style="color: red">{{ error_msg }}</span>
</form>
</body>
</html>
2.4 浏览器访问/login/
填写数据后,提交。
返回403,原因是缺少CSRF cookie;Django框架相比Flask框架默认多了一道CSRF的安全验证。
所以要在HTML文件的表单里,加上CSRF cookie 的验证,如下:
<h2>用户登录</h2>
<form method="post" action="/login/">
{% csrf_token %}
<input type="text" name="username" placeholder="用户名">
<input type="password" name="password" placeholder="密码">
<input type="submit" value="提交">
<span style="color: red">{{ error_msg }}</span>
</form>
2.5 浏览器访问登录页面
登录成功:
登录失败: