django框架之請求生命週期及ORM引入等相關內容-61
阿新 • • 發佈:2020-11-23
1 登入功能,連線mysql
路由
url(r'^login', views2.login),
url(r'^index', views2.index),
url(r'^test', views.test),
檢視函式
def index(request):
return render(request, 'index2.html')
def login(request):
if request.method == 'GET':
return render(request, 'login.html')
else:
name = request.POST.get('name')
password = request.POST.get('password')
# 建立一個數據庫連結
conn = pymysql.connect(host='127.0.0.1', user='root', password='123', database='userinfo', port=3306, )
# 拿到一個遊標
cursor = conn.cursor()
# 執行sql
cursor.execute('select * from user where name=%s and password=%s ', (name, password))
# 獲取結果
ret = cursor.fetchone()
print(ret)
if ret:
return redirect('/index')
else:
return HttpResponse('使用者名稱或密碼錯誤')
模板檔案login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="/static/bootstrap/css/bootstrap.css">
<title>Title</title>
</head>
<body>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h1 class="text-center">登入功能</h1>
<form action="" method="post">
<div class="form-group">
<label for="">使用者名稱:</label>
<input type="text" name="name" class="form-control">
</div>
<div class="form-group">
<label for="">密碼:</label>
<input type="password" name="password" class="form-control">
</div>
<div class="text-center">
<input type="submit" value="登入" class="btn btn-success">
</div>
</form>
</div>
</div>
</body>
</html>
模板檔案index2.html