django搭建BBS-登入&验证码的生成

基于注册完成后

文件结构

  • app 接口

    • migrations
    • __inint__.py
    • admin.py 管理员页面注册表单用
    • apps.py
    • bbsform.py form组件相关设置
    • models.py 模型存放
    • tests.py
    • views.py 业务逻辑
  • avatar 图片文件存储
  • BBS 项目名称以及路由存放
    • __inint__.py
    • settings.py
    • urls.py
    • wsgi.py
  • static
    • bootstrap-3.3.7-dist bootstrap文件网上下载的
    • jquery-3.4.1.min.js jq文件
  • templates 页面文件存放

一.创建图片验证

1.路由

urls.py

from django.conf.urls import url
from django.contrib import admin
#主路由导入视图内函数
from app import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^register/', views.register),
url(r'^login/', views.login),
url(r'^get_code/', views.get_code),
]

2.逻辑业务

views.py

from django.shortcuts import render,HttpResponse,redirect
from django.http import JsonResponse
#Image导入
#ImageDraw在图片上写字
#ImageFont 写字的格式
from PIL import Image,ImageDraw,ImageFont
import random
# 相当于把文件以byte格式存到内存中
from io import BytesIO from django.contrib import auth from app.bbsforms import Register
from app import models from django.db.models import Count
from django.db.models.functions import TruncMonth
from django.db.models import F # Create your views here.
def register(request):
if request.method=='GET':
form=Register()
return render(request,'register.html',{'form':form})
elif request.is_ajax():
response={'code':100,'msg':None}
form = Register(request.POST)
if form.is_valid():
#校验通过的数据
clean_data=form.cleaned_data
#把re_pwd剔除
clean_data.pop('re_pwd')
#取出头像
avatar=request.FILES.get('avatar')
if avatar:
#因为用的是FileField,只需要把文件对象赋值给avatar字段,自动做保存
clean_data['avatar']=avatar
user=models.UserInfo.objects.create_user(**clean_data)
if user:
response['msg'] = '创建成功'
else:
response['code'] = 103
# 把校验不通过的数据返回
response['msg'] = '创建失败'
else:
response['code']=101
#把校验不通过的数据返回
response['msg']=form.errors
print(type(form.errors))
return JsonResponse(response,safe=False) def login(request):
if request.method=='GET':
return render(request,'login.html') def get_code(request):
if request.method == 'GET':
img = Image.new('RGB', (350, 40), (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
# 写文字
# 生成一个字体对象
font = ImageFont.truetype('/static/Gabriola.ttf', 34)
# 调用方法,返回一个画板对象
draw = ImageDraw.Draw(img) new_text =''
# 生成随机8位数字
for x_index in range(1, 8):
num = chr(random.randint(48, 57))
word = chr(random.randint(65, 90))
word_1 = chr(random.randint(97, 122))
text =random.choice((num, word, word_1))
draw.text((x_index * 32, 0),text, font=font)
new_text +=text # 加点线
width = 320
height = 35
for i in range(5):
x1 = random.randint(0, width)
x2 = random.randint(0, width)
y1 = random.randint(0, height)
y2 = random.randint(0, height)
# 在图片上画线
draw.line((x1, y1, x2, y2), fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))) for i in range(33):
# 画点
draw.point([random.randint(0, width), random.randint(0, height)], fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
x = random.randint(0, width)
y = random.randint(0, height)
# 画弧形
draw.arc((x, y, x + 4, y + 4), 0, 90, fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
print(new_text)
#存在session中
request.session['code']=new_text
#存内存
f = BytesIO()
img.save(f, 'png')
return HttpResponse(f.getvalue())

3.网页

login.html

<!DOCTYPE html>
<html lang="en">
<head>
{% include 'bootstrap.html' %}<--载入bootstrap-->
<meta charset="UTF-8">
<title>登入</title>
</head>
<body>
<div class="container-fluid center-block">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h1>登陆</h1>
<form action="">
<div class="form-group">
<label for="id_name">用户名</label>
<input type="text" name="name" id="id_name" class="form-control">
</div>
<div class="form-group">
<label for="pwd">密码</label>
<input type="password" name="pwd" id="pwd" class="form-control">
</div>
<div class="form-group">
<label for="id_code">验证码</label>
<div class="row">
<div class="col-md-6">
<input type="text" name="code" id="id_code" class="form-control">
</div>
<div class="col-md-6" id="img">
<img src="/get_code/" height="40" width="350" class="img-code">
</div>
</div>
</div>
<input type="submit" value="提交" class="btn-success">
</form>
</div>
</div>
</div>
</body>
{% include 'jq.html' %} <--载入jq-->
<script> <--利用img标标签属性src发送改变后会自己去找-->
$('.img-code').click(function () {
var img_code_src = $(this).attr('src');
img_code_src += '1';
console.log(img_code_src);
$(this).attr('src',img_code_src)
})
</script>
</html>

二.账号信息进行验证

login.html

<!DOCTYPE html>
<html lang="en">
<head>
{% include 'bootstrap.html' %}
<meta charset="UTF-8">
<title>登入</title>
</head>
<body>
<div class="container-fluid center-block">
<div class="row">
<div class="col-md-6 col-md-offset-3">
{% csrf_token %}
<h1>登陆</h1>
<form action="">
<div class="form-group">
<label for="id_name">用户名</label>
<input type="text" name="name" id="id_name" class="form-control">
</div>
<div class="form-group">
<label for="pwd">密码</label>
<input type="password" name="pwd" id="pwd" class="form-control">
</div>
<div class="form-group">
<label for="id_code">验证码</label>
<div class="row">
<div class="col-md-6">
<input type="text" name="code" id="id_code" class="form-control">
</div>
<div class="col-md-6" id="img">
<img src="/get_code/" height="40" width="350" class="img-code">
</div>
</div>
</div>
<input type="button" value="提交" class="btn-success" id="up_data">
<span style="color: red" id="msg"></span>
</form>
</div>
</div>
</div>
</body>
{% include 'jq.html' %}
<script>
$('.img-code').click(function () {
var img_code_src = $(this).attr('src');
img_code_src += '1';
console.log(img_code_src);
$(this).attr('src',img_code_src)
})
</script> <script>
$('#up_data').click(function () {
$.ajax({
type:'post',
url:'/login/',
data:{'name':$('#id_name').val(),
'pwd':$('#pwd').val(),
'code':$('#id_code').val(),
'csrfmiddlewaretoken':'{{csrf_token}}'
},
success:function (msg) {
console.log(msg);
$('#msg').text(msg);
if (msg =='登入成功'){
console.log('sb');
window.location.replace('http://www.baidu.com');<--暂时先放百度-->
}
}
})
})
</script>
</html>

views.py

from django.shortcuts import render,HttpResponse,redirect
from django.http import JsonResponse
#Image导入
#ImageDraw在图片上写字
#ImageFont 写字的格式
from PIL import Image,ImageDraw,ImageFont
import random
# 相当于把文件以byte格式存到内存中
from io import BytesIO from django.contrib import auth from app.bbsforms import Register
from app import models from django.db.models import Count
from django.db.models.functions import TruncMonth
from django.db.models import F # Create your views here.
def register(request):
if request.method=='GET':
form=Register()
return render(request,'register.html',{'form':form})
elif request.is_ajax():
response={'code':100,'msg':None}
form = Register(request.POST)
if form.is_valid():
#校验通过的数据
clean_data=form.cleaned_data
#把re_pwd剔除
clean_data.pop('re_pwd')
#取出头像
avatar=request.FILES.get('avatar')
if avatar:
#因为用的是FileField,只需要把文件对象赋值给avatar字段,自动做保存
clean_data['avatar']=avatar
user=models.UserInfo.objects.create_user(**clean_data)
if user:
response['msg'] = '创建成功'
else:
response['code'] = 103
# 把校验不通过的数据返回
response['msg'] = '创建失败'
else:
response['code']=101
#把校验不通过的数据返回
response['msg']=form.errors
print(type(form.errors))
return JsonResponse(response,safe=False) def login(request):
if request.method=='GET':
return render(request,'login.html')
else:
print(request.POST)
user_name=request.POST.get('name')
pwd=request.POST.get('pwd')
code=request.POST.get('code') user=auth.authenticate(username=user_name,password=pwd)
print(user)
if request.session.get('code').upper() !=code.upper(): #忽略大小写
return HttpResponse('验证码错误')
elif not user:
return HttpResponse('账号密码错误')
else:
return HttpResponse('登入成功') def get_code(request):
if request.method == 'GET':
img = Image.new('RGB', (350, 40), (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
# 写文字
# 生成一个字体对象
font = ImageFont.truetype('/static/Gabriola.ttf', 34)
# 调用方法,返回一个画板对象
draw = ImageDraw.Draw(img) new_text =''
# 生成随机8位数字
for x_index in range(1, 8):
num = chr(random.randint(48, 57))
word = chr(random.randint(65, 90))
word_1 = chr(random.randint(97, 122))
text =random.choice((num, word, word_1))
draw.text((x_index * 32, 0),text, font=font)
new_text +=text # 加点线
width = 320
height = 35
for i in range(5):
x1 = random.randint(0, width)
x2 = random.randint(0, width)
y1 = random.randint(0, height)
y2 = random.randint(0, height)
# 在图片上画线
draw.line((x1, y1, x2, y2), fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))) for i in range(33):
# 画点
draw.point([random.randint(0, width), random.randint(0, height)], fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
x = random.randint(0, width)
y = random.randint(0, height)
# 画弧形
draw.arc((x, y, x + 4, y + 4), 0, 90, fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
print(new_text)
#存在session中
request.session['code']=new_text
#存内存
f = BytesIO()
img.save(f, 'png')
return HttpResponse(f.getvalue())

django搭建BBS-登入&验证码的生成的更多相关文章

  1. 网页登入验证码的实现(java&html)

    前端界面实现(由于验证码是动态获取所以用jsp格式) <%@ page language="java" contentType="text/html; charse ...

  2. discuz之同步登入

    前言   首先感谢dozer学长吧UCenter翻译成C# 博客地址----------->http://www.dozer.cc/   其次感谢群友快乐々止境同学的热心指导,虽然萍水相逢但让我 ...

  3. Django之动态验证码的生成

    kind.html <!DOCTYPE html> <html lang="en"> <head> <meta charset=" ...

  4. [Django]登陆界面以及用户登入登出权限

    前言:简单的登陆界面展现,以及用户登陆登出,最后用户权限的问题 正文: 首先需要在settings.py设置ROOT_URLCONF,默认值为: ROOT_URLCONF  = 'www.urls'# ...

  5. Python爬虫-尝试使用人工和OCR处理验证码模拟登入

    刚开始在网上看别人一直在说知乎登入首页有有倒立的汉字验证码,我打开自己的知乎登入页面,发现只有账号和密码,他们说的倒立的验证码去哪了,后面仔细一想我之前登入过知乎,应该在本地存在cookies,然后我 ...

  6. django 使用其自带的验证系统 进行用户名有效性验证 登录状态验证 登入操作 登出操作

    from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, l ...

  7. Django,COOKIES,SESSION完成用户登入

    1.urls.py """Django_cookie_session URL Configuration The `urlpatterns` list routes UR ...

  8. SpringBoot整合SpringSecurity简单实现登入登出从零搭建

    技术栈 : SpringBoot + SpringSecurity + jpa + freemark ,完整项目地址 : https://github.com/EalenXie/spring-secu ...

  9. Django之验证码的生成和使用

    1.基于PIL生成一个带验证码的图片和验证码,生成验证码图片需要Monaco.ttf字体,可按自己要求更改check_code中的字体和字体文件位置,如下图 #!/usr/bin/env python ...

随机推荐

  1. SAP压缩excel并发送mail案例

    "SAP压缩附件 REPORT ZMMR0033_DEL7 . TYPES: BEGIN OF bin_file,            name TYPE string,          ...

  2. .Net基础篇_学习笔记_第六天_for循环的嵌套_乘法口诀表

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  3. springmvc request foward 和 redirect

    ---恢复内容开始--- 最近在实现那个学生信息录入的时候,先是在添加学生的页面添加完,然后想直接调用Conroller层遍历学生的方法,我的意思就是在contoller一个方法怎么直接调用另外一个方 ...

  4. 61 (OC)* 代理 block 通知 代理 kvo

    1.从源头上理解和区别block和delegate delegate运行成本低,block的运行成本高. block出栈需要将使用的数据从栈内存拷贝到堆内存,当然对象的话就是加计数,使用完或者bloc ...

  5. 19 (OC)* RunLoop

    面试题 1:讲讲RunLoop,项目中有用到吗? 2:RunLoop内部实现逻辑? 3:Runloop和线程的关系? 4:timer 与 Runloop 的关系? 5:程序中添加每3秒响应一次的NST ...

  6. go 学习笔记之仅仅需要一个示例就能讲清楚什么闭包

    本篇文章是 Go 语言学习笔记之函数式编程系列文章的第二篇,上一篇介绍了函数基础,这一篇文章重点介绍函数的重要应用之一: 闭包 空谈误国,实干兴邦,以具体代码示例为基础讲解什么是闭包以及为什么需要闭包 ...

  7. vue2.0搭建vue手脚架(vue-cli)

    1.安装node.js 从node官网下载并安装node,安装步骤很简单,只要一路“next”就可以了.安装完成后,打开命令行工具输入命令node -v,如下图,如果出现对应版本号,就说明安装成功了. ...

  8. html中的空格

    网上摘录: HTML提供了6种空格实体.除第一种外,其他几种空格在不同浏览器中宽度各异.               它叫不换行空格,全称No-Break Space,它是最常见和我们使用最多的空格, ...

  9. maven仓库 - nexus配置

    搭建环境: 腾讯云服务器 CentOS 6.8.jdk7.sonatype nexus.maven.Xshell 5 版本信息: jdk : jdk-7u80-linux-x64.tar.gz nex ...

  10. 转:LinkedHashMap和HashMap的比较使用

    import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.uti ...