一、注册
1.注册之前端页面
html
复制代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册页面</title>
<!--动态引入文件-->
{% load static %}
<script src="{% static 'js/jquery.min.js' %}"></script>
<link href="{% static 'bootstrap/css/bootstrap.min.css' %}" rel="stylesheet">
<script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script>
<script src="{% static 'layer/layer.js' %}"></script>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-image: url('https://pegasus.epweike.com/Public/uploads/introduce/55dc0c8c010df.jpg');
background-size: cover;
background-repeat: no-repeat;
background-position: center;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.container {
background-color: rgba(255, 255, 255, 0.9);
border-radius: 10px;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
padding: 20px;
text-align: center;
width: 100%;
max-width: 600px;
}
h1 {
margin-top: 0;
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
font-weight: bold;
}
.form-control {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}
.btn {
background-color: #007bff;
color: #fff;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
width: 100%;
}
.btn:hover {
background-color: #0056b3;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h1 class="text-center">注册页面</h1>
<div class="form-group">
<label for="username">用户姓名</label>
<input type="text" id="username" class="form-control" msg="用户名必须填写">
</div>
<div class="form-group">
<label for="username">用户密码</label>
<input type="password" id="password" class="form-control" msg="密码必须填写">
</div>
<div class="form-group">
<label for="username">确认密码</label>
<input type="password" id="re_password" class="form-control" msg="确认密码必须填写">
</div>
<div class="form-group">
<label for="username">邮箱</label>
<input type="text" id="email" class="form-control" msg="邮箱必须填写">
</div>
<div class="form-group">
<label for="myfile">上传头像:
<img src="/static/img/default.png" id="myImg" width="100" alt="">
</label>
<input type="file" id="myfile" style="display: none" class="form-control">
</div>
<div class="form-group">
<input type="button" value="提交" class="btn btn-primary btn-block">
</div>
</div>
</div>
</div>
{# 绑定点击事件 #}
<script>
// 在页面显示图片
$("#myfile").change(function () {
// 1.需要借助于文件阅读器(JavaScript的)
let myFileReaderObj = new FileReader();
// 2.获取文件数据,在此处可以将#myfile改为this
{#var myFileDataObj = $("#myfile")[0].files[0];#}
var myFileDataObj = $(this)[0].files[0];
// 3.把获取到的文件数据提交给阅读器来获取图片
myFileReaderObj.readAsDataURL(myFileDataObj); // 这是异步提交
// 4.把它读取的文件数据放到img的src中
// 由于异步提交的缘故,代码会一直往下走,从而导致图片不能加载出来,
// 故而为了防止此类事件的发生,用onload等待文件或图片加载完再接着往下执行
myFileReaderObj.onload = function () {
$("#myImg").attr('src', myFileReaderObj.result);
}
});
$(".btn").click(function () {
// 1.获取表单数据
let username = $("#username").val();
let password = $("#password").val();
let re_password = $("#re_password").val();
let email = $("#email").val();
// 获取头像数据
let myImg = $("#myfile")[0].files[0];
console.log(myImg)
// 2.参数验证
//方式2:在input中写入 msg="用户名必须填写"等,然后循环取值
var ids = ['username', 'password', 're_password', 'email'];
$.each(ids, function (index, value) {
if (!$('#' + value).val()) {
layer.msg($("#" + value).attr('msg'));
return;
}
});
if (re_password !== password) {
layer.msg('两次密码不一致');
return;
}
// 由于是文件类型,所以data还要接收forData对象,接收了forData对象,
// contentType参数和processData参数则要设置为false
let formData = new FormData();
formData.append('username', username);
formData.append('password', password);
formData.append('re_password', re_password);
formData.append('email', email);
formData.append('myfile', myImg);
formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');
// 3.发起Ajax请求
$.ajax({
url: '',
type: 'post',
data: formData,
contentType: false,
processData: false,
success: function (res) {
if (res.code === 200) {
{#layer.msg(res.msg, {'icon': 1}, function () {#}
layer.msg(res.msg, {}, function () {
location.href = res.url;
});
} else {
layer.msg(res.msg);
}
},
});
// 参数验证方式1:
/*
if (!username) {
layer.msg('用户名必须填写');
return;
}
if (!password) {
layer.msg('密码必须填写');
return;
}
if (!re_password) {
layer.msg('确认必须填写');
return;
}
if (!email) {
layer.msg('邮箱必须填写');
return;
}*/
});
</script>
</body>
</html>
2.注册之后台功能
python
复制代码
def register(request):
# auth_user表扩展之后auth模块依然是可以使用的,在这使用最原生的
# 判断是否为Ajax提交
# print(request.is_ajax())
if request.method == 'POST':
# 1.定义返回前端的json数据格式
back_dict = {'code': 200, 'msg': '注册成功', 'data': []}
# 2.接收前端提交过来的参数
username = request.POST.get('username')
password = request.POST.get('password')
re_password = request.POST.get('re_password')
email = request.POST.get('email')
myfile = request.FILES.get('myfile')
# 3.验证参数:尽量是先验证不合法性,即反着过来验证,
# 正向验证也可以,只是会嵌套很多的elif语句
if not username:
# 1xx 2xx 3xx 4xx 5xx等一般是响应状态码,而我们下面写的业务状态码(人为规定的)
back_dict['code'] = 1001
back_dict['msg'] = '用户名必填'
return JsonResponse(back_dict)
if not password:
back_dict['code'] = 1003
back_dict['msg'] = '密码必填'
return JsonResponse(back_dict)
if not re_password:
back_dict['code'] = 1004
back_dict['msg'] = '确认密码必填'
return JsonResponse(back_dict)
if password != re_password:
back_dict['code'] = 1002
back_dict['msg'] = '两次密码不一致'
return JsonResponse(back_dict)
if not email:
back_dict['code'] = 1005
back_dict['msg'] = '邮箱必填'
return JsonResponse(back_dict)
# if len(password) >= 6 and len(password) <=20:
# back_dict['code'] = 1000
# back_dict['msg'] = '密码必须是6-20位的'
# return JsonResponse(back_dict)
# 4.开设处理正常的业务逻辑
new_pwd = get_md5(password)
data_dict = {}
data_dict['username'] = username
data_dict['password'] = new_pwd[: 16]
data_dict['email'] = email
if myfile:
data_dict['avatar'] = myfile
# models.UserInfo.objects.create(username=username, password=new_pwd, email=email, avatar=myfile)
# 改为下述
models.UserInfo.objects.create(**data_dict)
# 5.返回前端数据
back_dict['url'] = '/login/'
return JsonResponse(back_dict)
return render(request, 'register.html', locals())
3.密码加密加盐
python
复制代码
# auth模块自带的
from django.conf import settings
# 密码加盐
import hashlib
def get_md5(password):
m = hashlib.md5()
pwd = password + settings.SECRET_KEY
m.update(pwd.encode('utf8'))
return m.hexdigest()
二、登录
1.登录之前端页面
html
复制代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册页面</title>
<!--动态引入文件-->
{% load static %}
<script src="{% static 'js/jquery.min.js' %}"></script>
<link href="{% static 'bootstrap/css/bootstrap.min.css' %}" rel="stylesheet">
<script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script>
<script src="{% static 'layer/layer.js' %}"></script>
{# background: url('https://img0.baidu.com/it/u=741268616,1401664941&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1691859600&t=5c5bee3052ecec363c1ecc2eea9ac3f7') no-repeat; background-size: 100% 130%;#}
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-image: url('https://pegasus.epweike.com/Public/uploads/introduce/55dc0c8c010df.jpg');
background-size: cover;
background-repeat: no-repeat;
background-position: center;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.container {
background-color: rgba(255, 255, 255, 0.9);
border-radius: 10px;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
padding: 20px;
text-align: center;
width: 100%;
max-width: 600px;
}
h1 {
margin-top: 0;
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
font-weight: bold;
}
.form-control {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}
.btn {
background-color: #007bff;
color: #fff;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
width: 100%;
}
.btn:hover {
background-color: #0056b3;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h1 class="text-center">登录页面</h1>
<div class="form-group">
<label for="username">用户姓名</label>
<input type="text" id="username" class="form-control" msg="用户名必须填写">
</div>
<div class="form-group">
<label for="username">用户密码</label>
<input type="password" id="password" class="form-control" msg="密码必须填写">
</div>
<div class="form-group">
<label for="username">验证码</label>
<div class="row">
<div class="col-md-6">
<input type="text" id="code" class="form-control" msg="验证码必须填写">
</div>
<div class="col-md-6">
<img src="/get_code/" style=" width: 160px; height: 35px;" alt="">
</div>
</div>
</div>
<div class="form-group">
<input type="button" value="提交" class="btn btn-primary btn-block">
</div>
</div>
</div>
</div>
<script>
$(".btn").click(function () {
// 1.获取表单数据
let username = $("#username").val();
let password = $("#password").val();
let code = $("#code").val();
// 2.参数验证
//方式2:在input中写入 msg="用户名必须填写"等,然后循环取值
var ids = ['username', 'password', 'code'];
$.each(ids, function (index, value) {
if (!$('#' + value).val()) {
layer.msg($("#" + value).attr('msg'));
return;
}
});
if (code.length !== 5) {
layer.msg('验证码输入不正确');
return;
}
// 3.发起Ajax请求
$.ajax({
url: '',
type: 'post',
data: {username: username, password: password, code: code, csrfmiddlewaretoken: '{{ csrf_token }}'},
success: function (res) {
if (res.code === 200) {
{#layer.msg(res.msg, {'icon': 1}, function () {#}
layer.msg(res.msg, {}, function () {
location.href = res.url;
});
} else {
layer.msg(res.msg, {});
}
},
});
});
</script>
</body>
</html>
2.登录之后端
python
复制代码
def login(request):
'''
验证码:一般是图片验证码,
短信验证码(平台)
滑动验证码(平台)
验证码的作用:人机识别,防止爬虫------->一般都需要登录之后才能访问
:param request:
:return:
'''
if request.method == 'POST':
# 1.返回json的数据格式
back_dict = {'code': 200, 'msg': '登录成功,3s之后自动跳转', 'data': []}
username = request.POST.get('username')
password = request.POST.get('password')
code = request.POST.get('code')
# 2.验证参数
if not username:
back_dict['code'] = 1006
back_dict['msg'] = '用户名必填'
return JsonResponse(back_dict)
if not password:
back_dict['code'] = 1007
back_dict['msg'] = '密码必填'
return JsonResponse(back_dict)
# 由于验证码可能有大小写组成,所以,需要全部设置为大写或者小写
if code.upper() != request.session.get('code').upper():
back_dict['code'] = 1008
back_dict['msg'] = '验证码必填'
return JsonResponse(back_dict)
# 4.业务逻辑处理
new_pwd = get_md5(password)
user_obj = models.UserInfo.objects.filter(username=username, password=new_pwd[: 16]).first()
if not user_obj:
back_dict['code'] = 1009
back_dict['msg'] = '用户名或者密码错误'
return JsonResponse(back_dict)
# 安全相关:密码加密,sql注入,xss攻击,csrf,撞库等
# 登录成功,保存用户状态
request.session['username'] = user_obj.username
request.session['id'] = user_obj.pk
back_dict['url'] = '/home/'
return JsonResponse(back_dict)
return render(request, 'login.html', locals())
2.登录之随机验证码
python
复制代码
"""
图片相关的模块
pip3 install pillow
"""
from PIL import Image, ImageDraw, ImageFont
"""
Image:生成图片
ImageDraw:能够在图片上乱涂乱画
ImageFont:控制字体样式
"""
from io import BytesIO, StringIO
"""
内存管理器模块
BytesIO:临时帮你存储数据 返回的时候数据是二进制
StringIO:临时帮你存储数据 返回的时候数据是字符串
"""
import random
def get_random():
return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
def get_code(request):
# 最终步骤4:写图片验证码
img_obj = Image.new('RGB', (430, 35), get_random())
img_draw = ImageDraw.Draw(img_obj) # 产生一个画笔对象
# 字体地址下载 https://www.zhaozi.cn/s/all/freebusiness/
img_font = ImageFont.truetype('static/font/yun.ttf', 30) # 字体样式 大小
# 随机验证码 五位数的随机验证码 数字 小写字母 大写字母
code = ''
for i in range(5):
random_upper = chr(random.randint(65, 90))
random_lower = chr(random.randint(97, 122))
random_int = str(random.randint(0, 9))
# 从上面三个里面随机选择一个
tmp = random.choice([random_lower, random_upper, random_int])
# 将产生的随机字符串写入到图片上
"""
为什么一个个写而不是生成好了之后再写
因为一个个写能够控制每个字体的间隙 而生成好之后再写的话
间隙就没法控制了
"""
img_draw.text((i * 60 + 60, -2), tmp, get_random(), img_font)
# 拼接随机字符串
code += tmp
print(code)
# 随机验证码在登陆的视图函数里面需要用到 要比对 所以要找地方存起来并且其他视图函数也能拿到
request.session['code'] = code
io_obj = BytesIO()
img_obj.save(io_obj, 'png')
return HttpResponse(io_obj.getvalue())
三、首页
1.首页之前端(导航条和模态框)
html
复制代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
{% load static %}
<script src="{% static 'js/jquery.min.js' %}"></script>
<link href="{% static 'bootstrap/css/bootstrap.min.css' %}" rel="stylesheet">
<script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script>
<script src="{% static 'layer/layer.js' %}"></script>
</head>
<body>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">全球最大的博客网站</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="active"><a href="#">文章 <span class="sr-only">(current)</span></a></li>
<li><a href="#">分类</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
aria-expanded="false">点我看更多美女哦 <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li role="separator" class="divider"></li>
<li><a href="#">Separated link</a></li>
<li role="separator" class="divider"></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li>
</ul>
<form class="navbar-form navbar-left">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="submit" class="btn btn-default">搜索</button>
</form>
<!-- 模态框 -->
<ul class="nav navbar-nav navbar-right">
{% if request.session.username %}
<li><a href="#">{{ request.session.username }}</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
aria-expanded="false">更多操作 <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="#" data-toggle="modal" data-target=".bs-example-modal-lg">修改密码</a></li>
<li><a href="#">更改头像</a></li>
<li><a href="/logout/">退出登录</a></li>
<li><a href="#">后台管理</a></li>
</ul>
</li>
{% else %}
<li><a href="/login/">登录</a></li>
<li><a href="/register/">注册</a></li>
{% endif %}
</ul>
<div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="row">
<h1 class="text-center">修改密码</h1>
<div class="col-md-8 col-md-offset-2">
<div class="form-group">
用户名:<input type="text" readonly value="{{ request.session.username }}" class="form-control">
</div>
<div class="form-group">
原密码:<input type="password" id="old_password" class="form-control" msg="原密码必须输入">
</div>
<div class="form-group">
新密码:<input type="password" id="new_password" class="form-control" msg="原密码必须输入">
</div>
<div class="form-group">
确认密码:<input type="password" id="re_password" class="form-control" msg="原密码必须输入">
</div>
<div class="form-group">
<input type="button" value="修改密码" class="btn btn-primary btn-block">
</div>
</div>
</div>
</div>
</div>
</div>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<script>
$(".btn").click(function () {
// 1.获取参数
let old_password = $("#old_password").val();
let new_password = $("#new_password").val();
let re_password = $("#re_password").val();
// 2.参数验证
let ids = ['old_password', 'new_password', 're_password'];
$.each(ids, function (index, value) {
if (!$('#' + value).val()) {
layer.msg($('#' + value).attr('msg'));
return;
}
});
// 3.发起Ajax请求
$.ajax({
url: '/set_password/',
type: 'post',
data: {old_password:old_password, new_password:new_password, re_password:re_password, csrfmiddlewaretoken:'{{ csrf_token }}'},
success: function (res) {
if (res.code == 200) {
layer.msg(res.msg, {}, function () {
location.reload();
});
} else {
layer.msg(res.msg, {});
}
}
});
});
</script>
</body>
</html>
2.首页之后端(修改密码)
python
复制代码
def set_password(request):
if request.method == 'POST':
# 1.先设定给前端返回的json格式的数据
back_dict = {'code': 200, 'msg': '修改密码成功,3s后自动跳转', 'data': []}
# 2.接收前端提交过来的参数
old_password = request.POST.get('old_password')
new_password = request.POST.get('new_password')
re_password = request.POST.get('re_password')
# 3.验证参数
if new_password != re_password:
back_dict['code'] = 1200
back_dict['msg'] = '两次密码输入不一致'
return JsonResponse(back_dict)
# 验证老密码是否正确
old_pwd = get_md5(old_password)
user_obj = models.UserInfo.objects.filter(username=request.session.get('username'), password=old_pwd[: 16]).first()
if not user_obj:
back_dict['code'] = 1201
back_dict['msg'] = '原密码不正确'
return JsonResponse(back_dict)
# 4.修改新密码
new_pwd = get_md5(new_password)
print(new_pwd)
models.UserInfo.objects.filter(pk=request.session.get('id')).update(password=new_pwd[: 16])
return JsonResponse(back_dict)