当前位置: 首页 > news >正文

django登录注册案例(上)

创建项目并完成初始配置

settings.py中,配置templates和static

TEMPLATES = [{'BACKEND': 'django.template.backends.django.DjangoTemplates','DIRS': [os.path.join(BASE_DIR,'templates')],'APP_DIRS': True,'OPTIONS': {'context_processors': ['django.template.context_processors.debug','django.template.context_processors.request','django.contrib.auth.context_processors.auth','django.contrib.messages.context_processors.messages',],},},
]
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR,'static')]

在models.py中

from django.db import models
from datetime import datetime
# Create your models here.class User(models.Model):username = models.CharField(max_length=16) #用户名password = models.CharField(max_length=255) #密码is_delete = models.BooleanField(default=False) #逻辑删除字段create_time = models.DateTimeField(auto_now=datetime.now()) #注册时间

然后终端执行迁移命令

 python manage.py makemigrations
python manage.py migrate

navicat连接sqlite数据库

说明创建成功

然后在templates下面创建一个user文件夹,然后创建一个register.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>注册</title>
</head>
<body>
<form method="post" action="/register/">{% csrf_token %}用户名: <input type="text" name="username"><br>密码: <input type="password" name="pwd"><br>再次输入密码: <input type="password" name="cpwd"><br><input type="submit" value="注册">
</form>
</body>
</html>

views.py且对存入数据库中的密码进行哈希加密

from django.shortcuts import render
from django.http import JsonResponse
import re
import hashlib
from .models import User
# Create your views here.def index(request):return render(request,'index.html')def register(request):if request.method == "GET":return render(request,'user/register.html')elif request.method == "POST":#注册username = request.POST.get("username")pwd = request.POST.get("pwd")cpwd = request.POST.get("cpwd")#用户名不能重复is_exi = User.objects.filter(username=username).first()if is_exi:return JsonResponse({'code': -1, 'msg': "名字已存在,请另外取一个靓号!!"})if not all([username,pwd,cpwd]):return JsonResponse({'code': -1, 'msg': "有必填项未填写!!"})if pwd != cpwd:return JsonResponse({'code': -1, 'msg': "两次密码输入不一致!!"})if username.isdigit():return JsonResponse({'code':-1,'msg':"账号不能全为数字!!"})if not (6<=len(username)<=16):return JsonResponse({'code':-1,'msg':"账号为6-16位字符组成"})if not re.match('[0-9a-zA-Z]{8,16}',pwd):return JsonResponse({'code': -1, 'msg': "密码需要8-16位数字或者字母组成"})#存入数据u = User()u.username = username#todo: 对密码进行hashs = hashlib.sha1()s.update(pwd.encode("utf-8"))sha1_pwd = s.hexdigest()u.password = sha1_pwdu.save()return JsonResponse({'code': 200, 'msg': "注册成功"})

配置路由

url(r'^register/',register),

运行

查看数据库

 但是我们发现,使用submit点击提交会mor刷新页面,所以在这里我们用return false就会阻止默认行为,并触发前端Ajax请求。

要使用Ajax请求,首先得导入

<script src="/static/js/jquery-2.1.4.min.js" rel="script" type="application/javascript"></script>

所以修改register.py

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>注册</title><script src="/static/js/jquery-2.1.4.min.js" rel="script" type="application/javascript"></script>
</head>
<body>
<form>{% csrf_token %}用户名: <input type="text" name="username"><span style="color: red"></span> <br>密码: <input type="password" name="pwd"><span style="color: red"></span> <br>再次输入密码: <input type="password" name="cpwd"><span style="color: red"></span> <br>{#    <input type="submit" value="注册"> #}<input type="submit" value="注册" onclick="return false"> {# submit 默认会刷新页面,return false就会阻止默认行为 #}<span id="yangtuo" style="color: red"></span>
</form><script>$(function () {// 三个全局变量,表示是否验证通过is_erro_username = falseis_erro_pwd = falseis_erro_cpwd = false$("input[name='username']").blur(function () {check_name()})$("input[name='pwd']").blur(function () { // blur表示失去角点的时候触发check_pwd()})$("input[name='cpwd']").blur(function () { // blur表示失去角点的时候触发check_cpwd()})function check_name() {// blur表示失去角点的时候触发user = $("input[name='username']").val(){#console.log('用户名失去焦点', user)#}if (user == "") { // 如果用户名为空$("input[name='username']").next().html('用户名不能为空').show()is_erro_username = false // 表示验证不通过} else if (user.length < 6 || user.length > 16) {$("input[name='username']").next().html('用户名为6-16位').show()is_erro_username = false // 表示验证不通过} else { // 用户名不为空reg = /[0-9a-zA-Z]{6,16}/;if (reg.test(user)) { //正则能匹配,账号正确,隐藏提示$("input[name='username']").next().hide()is_erro_username = true // 表示验证通过} else { // 账号错误$("input[name='username']").next().html('账号为6-16位字符组成').show()is_erro_username = false // 表示验证不通过}}}function check_pwd() {user = $("input[name='pwd']").val()if (user == "") { // 如果密码为空$("input[name='pwd']").next().html('密码不能为空').show()is_erro_pwd = false // 表示验证不通过} else if (user.length < 8 || user.length > 16) {$("input[name='pwd']").next().html('密码为8-16位').show()is_erro_pwd = false // 表示验证不通过} else { // 密码不为空reg = /[0-9a-zA-Z]{8,16}/;if (reg.test(user)) { //正则能匹配,账号正确,隐藏提示$("input[name='pwd']").next().hide()is_erro_pwd = true // 表示验证通过} else { // 账号错误$("input[name='pwd']").next().html('密码为8-16位字符组成').show()is_erro_pwd = false // 表示验证不通过}}}function check_cpwd() {{#console.log('确认密码失去焦点')#}pwd = $("input[name='pwd']").val()cpwd = $("input[name='cpwd']").val()if (pwd !== cpwd) {$("input[name='cpwd']").next().html('两次输入密码不一致').show()is_erro_cpwd = false} else {$("input[name='cpwd']").next().hide()is_erro_cpwd = true}}$(':submit').click(function () {// console.log('点击了注册按钮')// 再次确认一下三个参数验证通过check_name();check_pwd();check_cpwd();console.log(is_erro_username, is_erro_cpwd, is_erro_pwd)if (is_erro_username && is_erro_cpwd && is_erro_pwd) { //都验证通过var username = $("input[name='username']").val()var pwd = $("input[name='pwd']").val()var cpwd = $("input[name='cpwd']").val()var csrf = $("input[name='csrfmiddlewaretoken']").val();// 发送ajax请求$.ajax({url: '/register/',data: {'username': username, 'pwd': pwd, 'cpwd': cpwd, 'csrfmiddlewaretoken': csrf},type: 'post',success: function (res) {console.log(res)if (res.code == 200){$(this).next().hide()//注册成功,跳转到主页window.location.href = '/'}else{// 注册失败$("#yangtuo").html(res.msg).show()}}})} else {  // 至少有一个验证不通过console.log('至少有一个验证不通过')return false}})})</script></body>
</html>

并创建一个主页index.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>主页</title>
</head>
<body>
<h1>欢迎您~</h1>
欢迎来到平平的课堂!
<a href="/register/">注册</a>
<a href="/login/">登录</a>
</body>
</html>

刷新

注册成功则跳转首页

输入:

跳转:

 


文章转载自:

http://lclTIKEJ.Lkpzx.cn
http://fa3Wcqwz.Lkpzx.cn
http://91lJfyCU.Lkpzx.cn
http://GSF6FEr5.Lkpzx.cn
http://n7dpmTWr.Lkpzx.cn
http://aqpLoQS5.Lkpzx.cn
http://BE3ZF43x.Lkpzx.cn
http://UfrRmddX.Lkpzx.cn
http://NjuYUCCf.Lkpzx.cn
http://OCYpNEIi.Lkpzx.cn
http://2GTLKDGS.Lkpzx.cn
http://WQrwP0OI.Lkpzx.cn
http://36Ylc9DL.Lkpzx.cn
http://1zKJQMDB.Lkpzx.cn
http://Fp0QzDbX.Lkpzx.cn
http://2Z6cU6ir.Lkpzx.cn
http://FO64gDix.Lkpzx.cn
http://mqG0VhnJ.Lkpzx.cn
http://kLDZPngy.Lkpzx.cn
http://9Doj9ETh.Lkpzx.cn
http://qzKL08a9.Lkpzx.cn
http://yYdQgiIg.Lkpzx.cn
http://p10KmJIA.Lkpzx.cn
http://ncjSmNrI.Lkpzx.cn
http://JNglR9ro.Lkpzx.cn
http://cVyYkzIb.Lkpzx.cn
http://gZh1kcLo.Lkpzx.cn
http://Nj1xJtZU.Lkpzx.cn
http://k7Ut3iJ9.Lkpzx.cn
http://sNvQ7Dgx.Lkpzx.cn
http://www.dtcms.com/a/384673.html

相关文章:

  • 查看iOS设备文件管理 访问iPhone用户文件、App沙盒目录 系统日志与缓存
  • 基于Echarts+HTML5可视化数据大屏展示-白茶大数据溯源平台V2
  • android 框架—网络访问Okhttp
  • CUDA 中Thrust exclusive_scan使用详解
  • Quat 四元数库使用教程:应用场景概述
  • GitHub 热榜项目 - 日榜(2025-09-15)
  • 让AI数据中心突破性能极限
  • Self-supervised Feature Adaptation for 3D Industrial Anomaly Detection 论文精读
  • 【3D图像算法技术讨论】如何给基于3dgs重建的城市街景增加碰撞的属性,满足仿真的要求?
  • numpy学习笔记
  • Oracle体系结构-归档日志文件(Archive Log Files)
  • 唐源电气:机器视觉与AI Agent引领智能运维
  • 【Python】在pycharm中使用environment.ylm文件配置虚拟环境
  • 2025前端面试题及答案-2(详细)
  • 技术突破:《Light Sci. Appl.》SH-GSL理论,为超表面提供全通道谐波调控能力
  • 2025年ASOC SCI2区TOP,多类别教学优化算法+多修剪机器人与多施肥无人机协同任务分配,深度解析+性能实测
  • 佰力博检测与您探讨高低温介电测试的应用领域
  • 网络编程-day6
  • 【04】AI辅助编程完整的安卓二次商业实战-寻找修改替换新UI首页图标-菜单图标-消息列表图标-优雅草伊凡
  • 《格式工厂FormatFactory》 [5.21.0][便携版] 下载
  • 【ubuntu24.04】安装rust
  • vue-sync修饰符解析以及切换iframe页面进行保存提示功能的思路
  • 005 Rust变量与常量
  • DOM---操作元素样式属性详解
  • Excel简单教程
  • Node.js 项目依赖包管理
  • LabVIEW命令行使用方法
  • 单变量单步时序预测 | TCN-LSTM时间卷积结合长短期记忆神经网络(MATLAB)
  • ESLint 自定义 Processor(处理器)
  • MySQL 极致性能优化指南——从 INSERT 到 UPDATE 的七大战场