一、注册
1.注册之前端页面
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 () {
let myFileReaderObj = new FileReader();
{#var myFileDataObj = $("#myfile")[0].files[0];#}
var myFileDataObj = $(this)[0].files[0];
myFileReaderObj.readAsDataURL(myFileDataObj);
myFileReaderObj.onload = function () {
$("#myImg").attr('src', myFileReaderObj.result);
}
});
$(".btn").click(function () {
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)
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;
}
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 }}');
$.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);
}
},
});
});
script>
body>
html>
2.注册之后台功能
def register(request):
if request.method == 'POST':
back_dict = {'code': 200, 'msg': '注册成功', 'data': []}
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')
if not username:
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)
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(**data_dict)
back_dict['url'] = '/login/'
return JsonResponse(back_dict)
return render(request, 'register.html', locals())
3.密码加密加盐
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.登录之前端页面
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 () {
let username = $("#username").val();
let password = $("#password").val();
let code = $("#code").val();
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;
}
$.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.登录之后端
def login(request):
'''
验证码:一般是图片验证码,
短信验证码(平台)
滑动验证码(平台)
验证码的作用:人机识别,防止爬虫------->一般都需要登录之后才能访问
:param request:
:return:
'''
if request.method == 'POST':
back_dict = {'code': 200, 'msg': '登录成功,3s之后自动跳转', 'data': []}
username = request.POST.get('username')
password = request.POST.get('password')
code = request.POST.get('code')
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)
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)
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.登录之随机验证码
"""
图片相关的模块
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):
img_obj = Image.new('RGB', (430, 35), get_random())
img_draw = ImageDraw.Draw(img_obj)
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.首页之前端(导航条和模态框)
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
{% 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">
<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 navigationspan>
<span class="icon-bar">span>
<span class="icon-bar">span>
<span class="icon-bar">span>
button>
<a class="navbar-brand" href="#">全球最大的博客网站a>
div>
<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="#">Actiona>li>
<li><a href="#">Another actiona>li>
<li><a href="#">Something else herea>li>
<li role="separator" class="divider">li>
<li><a href="#">Separated linka>li>
<li role="separator" class="divider">li>
<li><a href="#">One more separated linka>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>
div>
nav>
<script>
$(".btn").click(function () {
let old_password = $("#old_password").val();
let new_password = $("#new_password").val();
let re_password = $("#re_password").val();
let ids = ['old_password', 'new_password', 're_password'];
$.each(ids, function (index, value) {
if (!$('#' + value).val()) {
layer.msg($('#' + value).attr('msg'));
return;
}
});
$.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.首页之后端(修改密码)
def set_password(request):
if request.method == 'POST':
back_dict = {'code': 200, 'msg': '修改密码成功,3s后自动跳转', 'data': []}
old_password = request.POST.get('old_password')
new_password = request.POST.get('new_password')
re_password = request.POST.get('re_password')
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)
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)