Django实现登录注册
目录
配置路由
首先分发路由[User,Blog,Article]
python
from django.contrib import admin
from django.urls import path
from Blog import views
from django.conf.urls import include
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home, name='home'),
path('User/', include('User.urls', namespace='User')),
path('Blog/', include('Blog.urls', namespace='Blog')),
path('Article/', include('Article.urls', namespace='Article')),
]
配置路由
python
urlpatterns = [
path('register/', views.register, name='register'),
path('login/', views.login, name='login'),
# 返回图片路由
path('get_verify_img/', views.get_verify_img, name='get_verify_img'),
path('blog/', views.blog, name='blog'),
]
首页
python
def home(request):
if request.session.get('user'):
online_user = request.session.get('user')
else:
online_user = '登录'
return render(request, 'home.html', locals())
python
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- 引入jQuery-->
<script src="{% static 'js/jquery.js' %}"></script>
<!-- 引入Bootstrap的CSS文件-->
<link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
<!-- 引入Bootstrap的JavaScript文件-->
<script src="{% static 'js/bootstrap.js' %}"></script>
<!-- 引入 layui.css -->
<link rel="stylesheet" href="{% static 'layui/css/layui.css' %}">
<!-- 引入 layui.js -->
<script src="{% static 'layui/layui.js' %}"></script>
</head>
<body>
注册
前端:
html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- 引入jQuery-->
<script src="{% static 'js/jquery.js' %}"></script>
<!-- 引入Bootstrap的CSS文件-->
<link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
<!-- 引入Bootstrap的JavaScript文件-->
<script src="{% static 'js/bootstrap.js' %}"></script>
<!-- 引入 layui.css -->
<link rel="stylesheet" href="{% static 'layui/css/layui.css' %}">
<!-- 引入 layui.js -->
<script src="{% static 'layui/layui.js' %}"></script>
<style>
.content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div class="content">
<!-- 注册表单 -->
<form class="layui-form" method="post" onsubmit="return false;" id="lay_register">
{% csrf_token %}
<div class="demo-reg-container">
<div class="layui-form-item">
<div class="layui-row">
<div class="layui-col-xs7">
<div class="layui-input-wrap">
<div class="layui-input-prefix">
<i class="layui-icon layui-icon-cellphone"></i>
</div>
<input type="text" name="phone" value=""
lay-verify="required|phone" placeholder="手机号"
lay-reqtext="请填写手机号" autocomplete="off"
class="layui-input" id="reg-cellphone">
</div>
</div>
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-wrap">
<div class="layui-input-prefix">
<i class="layui-icon layui-icon-username"></i>
</div>
<input type="text" name="username" value="" lay-verify="required"
placeholder="用户名"
autocomplete="off"
class="layui-input" lay-affix="clear">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-wrap">
<div class="layui-input-prefix">
<i class="layui-icon layui-icon-password"></i>
</div>
<input type="password" name="password" value=""
lay-verify="required" placeholder="密码"
autocomplete="off" class="layui-input" id="reg-password"
lay-affix="eye">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-wrap">
<div class="layui-input-prefix">
<i class="layui-icon layui-icon-password"></i>
</div>
<input type="password" name="confirmPassword" value=""
lay-verify="required|confirmPassword"
placeholder="确认密码" autocomplete="off" class="layui-input"
lay-affix="eye">
</div>
</div>
<div class="layui-form-item">
<button class="layui-btn layui-btn-fluid" lay-submit
lay-filter="demo-reg" id="send_register">注册
</button>
</div>
<div class="layui-form-item demo-reg-other">
<a href="{% url 'Blog:login' %}">登录已有帐号</a>
</div>
</div>
</form>
</div>
<script>
layui.use(function () {
const $ = layui.$;
const form = layui.form;
const layer = layui.layer;
const util = layui.util;
util.on('lay-on', {
msg: function () {
{#layer.msg('登录成功');#}
}
})
// 自定义验证规则
form.verify({
// 确认密码
confirmPassword: function (value, item) {
const passwordValue = $('#reg-password').val();
if (value !== passwordValue) {
return '两次密码输入不一致';
}
}
});
});
{#注册事件#}
const registerButton = document.getElementById('send_register');
registerButton.addEventListener('click', function () {
// 获取表单元素
const form = document.getElementById('lay_register');
// 创建 FormData 对象
const formData = new FormData(form);
formData.append('index', 'register_modal')
$.ajax({
url: '',
type: 'POST',
processData: false, // 设为false防止JQuery自动将formData转成字符串
contentType: false, // 防止JQuery自动添加'Content-Type'请求头
{#data: JSON.stringify(newData),#}
data: formData,
success: function (data) {
if (data.err) {
layui.layer.msg(data.err)
}
if (data.info) {
layui.layer.msg('注册成功')
$(document.getElementById('register')).modal('hide')
window.open(data.info)
}
}
})
})
</script>
</body>
</html>
后端:
python
def register(request):
print('注册页面')
if request.method == 'POST' and request.is_ajax:
data = request.POST
username = data['username']
password = data['password']
phone = data['phone']
if models.Userinfo.objects.filter(username=username):
err_info = {'err': '用户名已存在'}
return JsonResponse(err_info)
else:
models.Userinfo.objects._create_user(username=username, password=password, phone=phone, email='')
back_info = {'info': 'http://127.0.0.1:8000/'}
return JsonResponse(back_info)
return render(request, 'register.html', locals())
登录
前端:
python
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- 引入jQuery-->
<script src="{% static 'js/jquery.js' %}"></script>
<!-- 引入Bootstrap的CSS文件-->
<link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
<!-- 引入Bootstrap的JavaScript文件-->
<script src="{% static 'js/bootstrap.js' %}"></script>
<!-- 引入 layui.css -->
<link rel="stylesheet" href="{% static 'layui/css/layui.css' %}">
<!-- 引入 layui.js -->
<script src="{% static 'layui/layui.js' %}"></script>
<style>
.content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div class="content">
<form class="layui-form" method="post" onsubmit="return false;" id="lay_login">
{% csrf_token %}
<div class="demo-reg-container">
<div class="layui-form-item">
<div class="layui-input-wrap">
<div class="layui-input-prefix">
<i class="layui-icon layui-icon-username"></i>
</div>
<input type="text" name="username" value="" lay-verify="required"
placeholder="用户名"
autocomplete="off"
class="layui-input" lay-affix="clear">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-wrap">
<div class="layui-input-prefix">
<i class="layui-icon layui-icon-password"></i>
</div>
<input type="password" name="password" value=""
lay-verify="required" placeholder="密码"
autocomplete="off" class="layui-input" id="reg-password"
lay-affix="eye">
</div>
</div>
<div class="layui-col-xs7">
<div class="layui-input-wrap">
<div class="layui-input-prefix">
<i class="layui-icon layui-icon-vercode"></i>
</div>
<input type="text" name="captcha" value="" lay-verify="required"
placeholder="验证码" lay-reqtext="请填写验证码"
autocomplete="off" class="layui-input" lay-affix="clear">
</div>
</div>
<div class="layui-col-xs5">
<div style="margin-left: 10px;">
<img src="{% url 'Blog:get_verify_img' %}" width="100%"
height="37px" id="img_verify" alt="">
</div>
</div>
<div class="layui-form-item">
<button class="layui-btn layui-btn-fluid" lay-submit
lay-filter="demo-reg" id="send_login" lay-on="msg">登录
</button>
</div>
<div class="layui-form-item demo-reg-other">
<a href="#">没有账号?立即注册</a>
</div>
</div>
</form>
</div>
<script>
{#刷新验证码#}
const verify = document.getElementById('img_verify')
verify.addEventListener('click', function () {
// 获取原始的 src 属性值
const verify_src = verify.src;
// 检查原始 src 是否已经包含时间戳
if (verify_src.includes('?')) {
// 如果已经包含时间戳,只替换最后一个时间戳
verify.src = verify_src.replace(/\?.*$/, '') + '?' + new Date().getTime();
} else {
// 如果原始 src 没有时间戳,直接添加时间戳
verify.src = verify_src + '?' + new Date().getTime();
}
})
{#登录事件#}
const loginButton = document.getElementById('send_login');
loginButton.addEventListener('click', function () {
// 获取表单元素
const form = document.getElementById('lay_login');
// 创建 FormData 对象
const formData = new FormData(form);
formData.append('index', 'login_modal')
$.ajax({
url: '',
type: 'POST',
processData: false, // 设为false防止JQuery自动将formData转成字符串
contentType: false, // 防止JQuery自动添加'Content-Type'请求头
data: formData,
success: function (data) {
if (data.err) {
layui.layer.msg(data.err)
}
if (data.url)
window.open(data.url)
},
error: function (xhr, status, error) {
console.log('error')
}
})
})
</script>
</body>
</html>
后端:
python
def login(request):
if request.method == 'POST' and request.is_ajax:
data = request.POST
user = models.Userinfo.objects.filter(username=data['username']).first()
if not user:
err_info = JsonResponse({'err': '用户不存在'})
return err_info
if not check_password(data['password'], user.password):
print('密码错误')
err_info = JsonResponse({'err': '密码错误'})
return err_info
else:
request.session['user'] = data['username']
return JsonResponse({'url': 'http://127.0.0.1:8000/'})
return render(request, 'login.html', locals())
验证码部分逻辑
python
def get_verify_img(request):
data, words = verify()
print(words)
return HttpResponse(data)
def random_rgb():
return random.randint(0, 256), random.randint(0, 256), random.randint(0, 256)
def random_word():
# 0-9数字
random_num = random.randint(0, 9)
# a-z
random_lower = chr(random.randint(97, 122))
# A-Z
random_upper = chr(random.randint(65, 90))
word = random.choice([random_upper, random_lower, str(random_num)])
return word