思路:
實現簡易的登陸、注冊,我們至少需要三個HTML頁面,一個主頁面、一個登陸界面、一個注冊界面。為了存儲和校驗用戶的賬號和密碼,我們需要寫一個模型類(用於映射到數據庫)、兩個form類(一個登陸、一個注冊,用戶校驗前端傳來的數據是否合法)、視圖函數、url配置。出於安全考慮,我們還要將密碼進行加密再存儲到數據庫,這里用的hash加密,django已封裝好了這個庫,位於django.contrib.auth.hashers中的make_password方法,還有個check_password方法用於檢驗加密前后的密碼是否屬於同一個。
模板代碼如下:
主頁模板
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>家目錄</title>
<style>
* {
padding: 0;
margin: 0;
}
</style>
</head>
<body>
你好 {{ username }} <br>
<a href = {% url 'baidu1_login' %} >登陸</a>
<a href = {% url 'baidu1_register' %}>注冊</a>
<a href = {% url 'baidu1_loginout' %}>退出</a>
</body>
</html>
注冊模板
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注冊</title>
<style>
div img{
display:inline-block;
width:130px;
height:80px;
vertical-align: 0px;
}
div p{
display: inline-block;
width:130px;
height:80px;
margin-left: 10px;
text-align:center;
line-height:50px;
vertical-align:33px;
}
input{
display: inline-block;
width:300px;
height:30px;
}
.four{
width:300px;
}
.yan{
width:181px;
height:36px;
}
#o666{
width:10px;
height:10px;
}
label{
font-size:12px;
vertical-align:1px;
}
.zhuce{
display:inline-block;
margin-left: 55px;
background-color:blue;
color:white;
padding:0px;
border-width:0px;
height:46px;
}
</style>
</head>
<body>
<div>
<img src="https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3572347546,3948256807&fm=27&gp=0.jpg" alt="logo">
<p>注冊百度賬號</p>
</div>
<form action = "" method = "post">
{% csrf_token %}
<p>用戶名 <input type = "text" name = "username" placeholder="請設置用戶名" ><span style ="color:red">{{ userform.username.errors.0 }}</span></p>
<p>密 碼 <input type="password" name = "password" placeholder="請設置登陸密碼" /><span style ="color:red">{{ userform.password.errors.0 }}</span></p>
<p>郵 箱 <input type = "text" name = 'email' placeholder="請輸入郵箱" class = "four"/> <span style ="color:red">{{ userform.email.errors.0 }}</span>
<p>
<input type = "checkbox" id = "o666">
<label for="o666">閱讀並接受《百度用戶協議》及《百度隱私權保護聲明》</label>
</p>
<p>
<input type = "submit" value = "注冊" class = "zhuce">
</p>
</form>
</body>
</html>
登陸模板:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登陸</title>
<style>
div img{
display:inline-block;
width:130px;
height:80px;
/*border: solid 5px red;*/
vertical-align: 0px;
}
div p{
/*border: solid 5px red;*/
display: inline-block;
width:130px;
height:80px;
margin-left: 10px;
/*padding-left:20px;*/
/*padding-top:20px;*/
text-align:center;
line-height:50px;
vertical-align:33px;
/*vertical-align: super;*/
}
input{
display: inline-block;
width:300px;
height:30px;
}
.four{
width:300px;
}
.yan{
width:181px;
height:36px;
}
#o666{
width:10px;
height:10px;
}
label{
font-size:12px;
vertical-align:1px;
}
.zhuce{
display:inline-block;
margin-left: 55px;
background-color:blue;
color:white;
padding:0px;
border-width:0px;
height:46px;
}
</style>
</head>
<body>
<div>
<img src="https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3572347546,3948256807&fm=27&gp=0.jpg" alt="logo">
<p>登陸百度賬號</p>
</div>
<form action = "" method = "post">
{% csrf_token %}
<p>用戶名 <input type = "text" name = "username" placeholder="請設置用戶名" /></p>
<p>密 碼 <input type="password" name = "password" placeholder="請設置登陸密碼" /></p>
<p>
<input type = "submit" value = "登陸" class = "zhuce">
</p>
</form>
</body>
</html>
app名為baidu,子路由分配如下:
from django.urls import path
from .import views
urlpatterns = [
path('home/',views.home,name = 'baidu1_home'),
path('login/',views.login,name = 'baidu1_login'),
path('register/',views.register,name = 'baidu1_register'),
path('loginout/',views.loginout,name = "baidu1_loginout"),
]
主路由分配:
path('baidu1/',include('baidu1.urls'))
模型類如下:
from django.db import models
# Create your models here.
class baidu_User(models.Model):
user_name = models.CharField(max_length=15,null=False,unique=True)
password = models.CharField(max_length=200)
email = models.EmailField()
form類如下:
from django import forms
class Register_form(forms.Form):
username = forms.CharField(required=True,min_length=6,max_length=15,error_messages={
'min_length':'用戶名長度不能低於6',
'max_length':'用戶名長度不能大於15',
'require':'用戶名不能空',
})
password = forms.CharField(min_length=6,required=True,error_messages={
'min_length':'密碼長度不能低於6',
'require':'密碼不能空',
})
email = forms.EmailField()
class Login_form(forms.Form):
username = forms.CharField(required=True, min_length=6, max_length=15, error_messages={
'min_length': '用戶名長度不能低於6',
'max_length': '用戶名長度不能大於15',
'require': '用戶名不能空',
})
password = forms.CharField(min_length=6, max_length=30, required=True, error_messages={
'min_length': '密碼長度不能低於6',
'require': '密碼不能空',
})
視圖函數如下:
from django.shortcuts import render,redirect,reverse
from django.http import HttpResponse
# -*- coding:utf-8 -*-
# Create your views here.
from .form import Register_form,Login_form
from .models import baidu_User
from django.contrib.auth.hashers import make_password,check_password
def home(request):
username = request.session.get('username','游客') #默認是游客
return render(request,'baidu1/home.html',context={
'username':username,
})
def login(request):
if request.method == "GET":
return render(request,'baidu1/login.html')
elif request.method == 'POST':
User_form = Login_form(request.POST)
if User_form.is_valid():
username = User_form.cleaned_data.get('username')
password = User_form.cleaned_data.get('password')
user = baidu_User.objects.filter(user_name=username)
if user:
if (check_password(password,user[0].password)): #驗證密碼的正確性
request.session['username'] = username #服務端返回一個sessionid給客戶端
return render(request,'baidu1/home.html',context={
'username':username
})
else:
return redirect(reverse('baidu1_login'))
else:
return render(request, reverse('baidu1_login'), context={
'userform': User_form,
})
else:
return HttpResponse("error")
def register(request):
if request.method == 'GET':
return render(request,'baidu1/register.html')
elif request.method == 'POST':
User_form = Register_form(request.POST)
if User_form.is_valid():
username = User_form.cleaned_data.get('username')
password = User_form.cleaned_data.get('password')
password = make_password(password) #密碼加密
email = User_form.cleaned_data.get('email')
user =baidu_User(user_name = username,password = password,email = email)
user.save() #保存到數據庫
return HttpResponse("注冊成功")
else:
return render(request,'baidu1/register.html',context={
'userform':User_form,
})
else:
return HttpResponse('ERROR')
def loginout(request):
request.session.flush() #清除當前會話,即退出當前用戶
return redirect(reverse('baidu1_home'))
效果如下:
點擊注冊,輸入用戶名223,密碼123,發現界面提示數據不合法。
再次輸入合法的數據,即可成功進行注冊。
打開數據庫,可以發現密碼已被加密。
進入登陸界面進行登陸
登陸后界面如下,此時用戶名已改變。
打開存儲在本地的cookies,發現服務端發來了一個sessionid。