欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-08 18:51:49
django搭建BBS 登入&验证码的生成 文件结构 app 接口 migrations _\_inint\_\_.py admin.py apps.py bbsform.py models.py tests.py views.py avatar BBS \_\_inint\_\_.py setti ......

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())