用戶注冊后端邏輯
1. 接收參數
username = request.POST.get('username')
password = request.POST.get('password')
password2 = request.POST.get('password2')
mobile = request.POST.get('mobile')
allow = request.POST.get('allow')
2. 校驗參數
from django import http
import re
# 判斷參數是否齊全
if not all([username, password, password2, mobile, allow]):
return http.HttpResponseBadRequest('缺少必傳參數')
# 判斷用戶名是否是5-20個字符
if not re.match(r'^[a-zA-Z0-9_]{5,20}$', username):
return http.HttpResponseBadRequest('請輸入5-20個字符的用戶名')
# 判斷密碼是否是8-20個數字
if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
return http.HttpResponseBadRequest('請輸入8-20位的密碼')
# 判斷兩次密碼是否一致
if password != password2:
return http.HttpResponseBadRequest('兩次輸入的密碼不一致')
# 判斷手機號是否合法
if not re.match(r'^1[3-9]\d{9}$', mobile):
return http.HttpResponseBadRequest('請輸入正確的手機號碼')
# 判斷是否勾選用戶協議
if allow != 'on':
return http.HttpResponseBadRequest('請勾選用戶協議')
這里校驗的參數,前端已經校驗過,如果此時參數還是出錯,說明該請求是非正常渠道發送的,所以直接禁止掉。
3. 保存注冊數據
from django.db import DatabaseError
# 保存注冊數據
try:
User.objects.create_user(username=username, password=password, mobile=mobile)
except DatabaseError:
return render(request, 'register.html', {'register_errmsg': '注冊失敗'})
# 響應注冊結果
return http.HttpResponse('注冊成功,重定向到首頁')
示例:重定向
from django.shortcuts import redirect
from django.urls import reverse
# 響應注冊結果
return redirect(reverse('contents:index'))
狀態保持
1. login()方法介紹
- 狀態保持:
- 將通過認證的用戶的唯一標識信息(比如:用戶ID)寫入到當前session會話中
- login()方法:
- Django用戶認證系統提供了
login()方法 - 封裝了寫入session的操作,幫助我們快速實現狀態保持
- Django用戶認證系統提供了
-
login()位置:
-
django.contrib.auth.__init__.py文件中login(request, user)
-
2. login()方法使用
# 保存注冊數據
try:
user = User.objects.create_user(username=username, password=password, mobile=mobile)
except DatabaseError:
return render(request, 'register.html', {'register_errmsg': '注冊失敗'})
# 實現狀態保持
login(request, user)
# 響應注冊結果
return redirect(reverse('contents:index'))
用戶名或手機號重復注冊邏輯:
1.請求方式
| 選項 | 方案 |
|---|---|
| 請求方法 | GET |
| 請求地址 | /usernames/(?P<username>[a-zA-Z0-9_]{5,20})/count/ |
用戶名重復注冊后端邏輯(通過filter過濾是否有重名用戶,count返回0或1,0說明沒注冊過,手機號重復注冊邏輯相同)
from utils.response_code import RETCODE
class UsernameCountView(View):
"""判斷用戶名是否重復注冊"""
def get(self, request, username):
"""
:param request: 請求對象
:param username: 用戶名
:return: JSON
"""
count = User.objects.filter(username=username).count()
return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})
前端邏輯:
//檢測用戶名是否存在
if (this.error_username == false) {
//拼接請求url
let url = '/usernames/' + this.username + '/count/';
axios.get(url,{
responseType: 'json'
})
.then(response => {
//請求成功的判斷
if (response.data.count == 1) {
this.error_username_message = '用戶名已存在';
this.error_username = true;
} else {
this.error_username = false;
}
})
.catch(error => {
//請求失敗顯示錯誤
console.log(error.response);
})
}
