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

django搭建BBS-登入&验证码的生成,第1张

概述django搭建BBS 登入&验证码的生成 文件结构 app 接口 migrations __inint__.py admin.py apps.py bbsform.py models. django搭建BBS-登入&验证码的生成

基于注册完成后

文件结构app 接口migrations__inint__.pyadmin.py 管理员页面注册表单用apps.pybbsform.py form组件相关设置models.py 模型存放tests.pyvIEws.py 业务逻辑avatar 图片文件存储BBS 项目名称以及路由存放__inint__.pysettings.pyurls.pywsgi.pystaticbootstrap-3.3.7-dist bootstrap文件网上下载的jquery-3.4.1.min.Js jq文件templates 页面文件存放一.创建图片验证1.路由

urls.py

from django.conf.urls import urlfrom django.contrib import admin#主路由导入视图内函数from app import vIEwsurlpatterns = [    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,redirectfrom django.http import JsonResponse#Image导入#ImageDraw在图片上写字#ImageFont 写字的格式from PIL import Image,ImageDraw,ImageFontimport random# 相当于把文件以byte格式存到内存中from io import BytesIOfrom django.contrib import authfrom app.bbsforms import Registerfrom app import modelsfrom django.db.models import Countfrom django.db.models.functions import TruncMonthfrom 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)))        # 写文字        # 生成一个字体对象        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)))        for i in range(33):            # 画点            draw.point([random.randint(0,wIDth),height)],255)))            x = random.randint(0,wIDth)            y = random.randint(0,height)            # 画弧形            draw.arc((x,y,x + 4,y + 4),90,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 >    <div >        <div >            <h1>登陆</h1>            <form action="">                <div >                    <label for="ID_name">用户名</label>                    <input type="text" name="name" ID="ID_name" >                </div>                <div >                    <label for="pwd">密码</label>                    <input type="password" name="pwd" ID="pwd" >                </div>                <div >                    <label for="ID_code">验证码</label>                    <div >                        <div >                            <input type="text" name="code" ID="ID_code" >                        </div>                        <div  ID="img">                            <img src="/get_code/" height="40" wIDth="350" >                        </div>                    </div>                </div>                <input type="submit" value="提交" >            </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 >    <div >        <div >            {% csrf_token %}            <h1>登陆</h1>            <form action="">                <div >                    <label for="ID_name">用户名</label>                    <input type="text" name="name" ID="ID_name" >                </div>                <div >                    <label for="pwd">密码</label>                    <input type="password" name="pwd" ID="pwd" >                </div>                <div >                    <label for="ID_code">验证码</label>                    <div >                        <div >                            <input type="text" name="code" ID="ID_code" >                        </div>                        <div  ID="img">                            <img src="/get_code/" height="40" wIDth="350" >                        </div>                    </div>                </div>                <input type="button" value="提交"  ID="up_data">                <span  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,'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','png')        return httpResponse(f.getvalue())
总结

以上是内存溢出为你收集整理的django搭建BBS-登入&验证码的生成全部内容,希望文章能够帮你解决django搭建BBS-登入&验证码的生成所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1222931.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存