VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • 【django入门】 04 初探GET/POST 设计登录页面

理解GET请求/POST请求

(大写的GET,大写的POST)
简单来说,GET就是输入网址访问(可依靠网址显式传递参数);POST就是提交表单访问(隐式传递参数

  • request是可变自定义变量名,它包括method属性(等于GET或POST)
  • request.GET 为显式传递的参数 (大写的GET)
  • request.POST 为隐式传递的参数 (大写的POST)

 
print(request.method)
 
print(request.GET)
 
print(request.POST)

三种return:

  1. return HttpResponse("welcome")
  2. return render(request, "index.html", {"varHtml": var})
  3. return redirect("www.baidu.com")

设计登录 请求/响应

  • views.py
    • 第3行:GET要大写
    • 第5行:当非GET时,才会运行到这一行
    • 第6行:user来自html文件form中对用户名input的命名,是user
    • 第6行:获取用户POST请求中参数的语法,是POST.get("user")
    • 第11行:如运行到此,则传入带值变量(“密码错误”)——html中一直有渲染此变量,只是之前默认为空

 
def index(request):
 
 
 
if request.method == "GET":
 
return render(request, "index.html")
 
 
 
username = request.POST.get("user")
 
password = request.POST.get("pwd")
 
if username == "trueName" and password == "123":
 
return HttpResponse("登录成功")
 
 
 
return render(request,"index.html", {"error_msg": "密码错误"})

 

  • index.html
    • 第3行:如写为action="",效果为返回本页,即,同action="/index/"——左右"/"都不可少
    • 第3行:action不可省略左"/",否则返回网址在"index/"后额外又加一个"index/"
    • 第3行:action不可省略右"/",否则报错,因为网址必须以"/"截止
    • 第4行:<form>里的{% csrf_token %}不可少;csrf = Cross Site Request Forgery
    • 第567行:html语法,两种叫placesholder,一种叫value
    • 第8行:html语法,需在一个框架里,比如,才可设定style = "color:red"

 
<body>
 
<h1>登录</h1>
 
<form method="post" action="/index/">
 
{% csrf_token %} #验证
 
<input type="text" name="user" placeholder="用户名">
 
<input type="password" name="pwd" placeholder="密码">
 
<input type="submit" value="提交">
 
<span style="color: red">{{ error_msg }} </span>
 
</form>
 
</body>

来源:BV1NL41157 武沛齐《2022 B站最详细django3教程(django从入门到实践)》P11


相关教程