重定向
介绍
redirect 是Django的内部方法,他可以将用户发来的请求重定向到另外一个URL上,他可以重定向到一完整的URL、视图
案例
登录完成后重定向到首页
-
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="http://127.0.0.1:8000/user/auth/" method="post"> # action参数也可以是一个相对路径 action="/user/auth/ 相对路路径最前面必须要加/ <body>用户名:<input type="text" name="user"></body> <body>密码:<input type="password" name="pwd"></body> <input type="submit"> <span>{{ msg }}</span> </form> </body> </html>
-
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h3>您好 {{ ip }}</h3> </body> </html>
-
urls
from django.urls import path,re_path from user.views import login,auth,index urlpatterns = [ path("", index), path("login/", login), path("auth/", auth), ]
-
视图 views
def index(request): return render(request,"user/index.html",{"ip":request.get_host()}) def login(request): return render(request, 'user/login.html') def auth(request): user = request.POST.get('user', None) pwd = request.POST.get('pwd',None) if user == "zhq" and pwd == "123": # return HttpResponse("登录成功") return redirect("/user/") # 重定向 else: # return redirect("/login/") # 重定向 msg = "用户名或者密码错误" return render(request,"user/login.html",{"msg":msg}) # 需要返回一个静态页面就没有必要重定向 使用render同样可以实现,这样还少一次请求
当访问login视图返回一个登录页面,输入用户名密码 点击提交 会调用auth视图,用户名密码校验成功重定向到首页index