一、注册模块
1.创建注册验证表单
from django import forms
from user.models import User
class UserRegisterForm(forms.Form):
user_name = forms.CharField(max_length=20, min_length=5, required=True,
error_messages={
'required': '用户名必填',
'max_length': '用户名不能超过20位字符',
'min_length': '用户名不能少于5位字符',
})
pwd = forms.CharField(max_length=20, min_length=8, required=True,
error_messages={
'required': '密码必填',
'max_length': '密码不能超过20位字符',
'min_length': '密码不能少于8位字符'
})
cpwd = forms.CharField(max_length=20, min_length=8, required=True,
error_messages={
'required': '确认密码必填',
'max_length': '密码不能超过20位字符',
'min_length': '密码不能少于8位字符'
})
email = forms.CharField(required=True,
error_messages={
'required': '邮箱必填'
})
# 验证时,会自动调用
def clean(self):
# 校验用户名是否已存在于数据库
user =User.objects.filter(username=self.cleaned_data.get('user_name')).first()
if user:
# 用户已存在于数据库,抛出异常
raise forms.ValidationError({'user_name': '该用户已存在'})
# 校验密码是否相等
pwd = self.cleaned_data.get('pwd')
cpwd = self.cleaned_data.get('cpwd')
if pwd != cpwd:
raise forms.ValidationError({'pwd': '两次密码不一致'})
return self.cleaned_data
2.注册功能
from django.contrib.auth.hashers import make_password, check_password
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from user.forms import UserRegisterForm, UserLoginForm
from user.models import User
def register(request):
if request.method == 'GET':
return render(request, 'register.html')
if request.method == 'POST':
# 使用表单做验证
form = UserRegisterForm(request.POST)
if form.is_valid():
# 字段验证成功,注册用户名不存在于数据库,密码和确认密码是一致的
username = form.cleaned_data['user_name']
password = form.cleaned_data['pwd']
email = form.cleaned_data['email']
# 密码加密:make_password()
# from django.contrib.auth.hashers import make_password
new_password = make_password(password)
User.objects.create(username=username, password=new_password, email=email)
return HttpResponseRedirect(reverse('user:login'))
else:
# 字段验证不成功,将验证失败的信息返回给页面
errors = form.errors
return render(request, 'register.html', {'errors': errors})
二、登录模块
1.创建登录验证表单
class UserLoginForm(forms.Form):
username = forms.CharField(required=True,
error_messages={
'required': '用户名必填',
})
pwd = forms.CharField(required=True,
error_messages={
'required': '密码必填',
})
2.登录功能
from django.contrib.auth.hashers import make_password, check_password
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from user.forms import UserRegisterForm, UserLoginForm
from user.models import User
def login(request):
if request.method == 'GET':
return render(request, 'login.html')
if request.method == 'POST':
# 使用表单验证
form = UserLoginForm(request.POST)
if form.is_valid():
# 验证字段成功
username = form.cleaned_data['username']
pwd = form.cleaned_data['pwd']
user = User.objects.filter(username=username).first()
if user:
# 校验密码是否一致
if check_password(pwd, user.password):
# 校验成功
request.session['user_id'] = user.id
return HttpResponseRedirect(reverse('goods:index'))
else:
# 密码错误
error_pwd = '账号或密码错误'
return render(request, 'login.html', {'error_pwd': error_pwd})
else:
error_pwd = '账号或密码错误'
return render(request, 'login.html', {'error_pwd': error_pwd})
else:
errors = form.errors
return render(request, 'login.html', {'errors': errors})
def user_center_info(request):
if request.method == 'GET':
return render(request, 'user_center_info.html')
def user_center_order(request):
if request.method == 'GET':
return render(request, 'user_center_order.html')
def user_center_site(request):
if request.method == 'GET':
return render(request, 'user_center_site.html')
三、中间件校验登录状态
1.定义校验中间件
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.utils.deprecation import MiddlewareMixin
from user.models import User
class LoginStatusMiddleware(MiddlewareMixin):
def process_request(self, request):
if request.path in [reverse('user:register'), reverse('user:login')]:
return None
user_id = request.session.get('user_id')
if user_id:
user = User.objects.get(pk=user_id)
request.user = user
return None
else:
return HttpResponseRedirect(reverse('user:login'))
def process_response(self, request, response):
return response
2.主页面模块
from django.shortcuts import render
from goods.models import Goods, GoodsCategory
from user.models import User
def index(request):
if request.method == 'GET':
data = {}
# 循环商品分类
for cate in GoodsCategory.CATEGORY_TYPE:
# 获取当前分类下的前四个商品信息
goods = Goods.objects.filter(category_id=cate[0])[0:4]
# 组装成键值对,key为商品分类的名称,value为当前分类的商品信息
data[cate[1]] = goods
return render(request, 'index.html', {'goods_category': data})
网友评论