Django-验证码

1.创建app

python manage.py startapp booktest

2.安装验证码库

# 安装验证码,图片包
pip install pillow

# 验证码库
pip install django-multi-captcha-admin django-simple-captcha

simple-captcha https://github.com/mbi/django-simple-captcha
recaptcha https://github.com/praekelt/django-recaptcha
recaptcha2 https://github.com/kbytesys/django-recaptcha2

 

3.setting添加booktest,同时添加验证码库multi_captcha_admin

INSTALLED_APPS = [
    'multi_captcha_admin',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'booktest',
]
# admin站点动态验证码
MULTI_CAPTCHA_ADMIN = {
    'engine': 'simple-captcha'
}

4. 验证码数据库迁移,否则显示不出来

python manage.py migrate

注:一定要迁移,admin才能显示验证码

5.配置跟目录的文件夹中的urls

from django.contrib import admin
from django.urls import path, re_path
from django.conf.urls import include

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'^captcha/', include('captcha.urls')),
    path('blog/', include('blog.urls')),
    # path('booktest/', include('booktest.urls', 'booktest')),
    # 2.0以后,反向解析使用以下方式
    path('booktest/', include(('booktest.urls', 'booktest'), namespace='booktest')),
]

6.配置booktest/urls

from django.urls import path, re_path
from . import views

urlpatterns = [
    re_path(r'^verifyCode$', views.verifyCode),
    re_path(r'^verifyTest1', views.verifyTest1),
    re_path(r'^verifyTest2', views.verifyTest2),

]

注:最新版本2.0以上使用path 或者re_path

 

7.编写视图

# coding=utf-8

from django.shortcuts import render
from django.http import HttpResponse
from booktest.models import HeroInfo
import logging


# 验证码
def verifyCode(request):
    from PIL import Image, ImageDraw, ImageFont
    import random
    # 创建背景色
    bgColor = (random.randrange(50, 100), random.randrange(50, 100), 0)
    # 规定宽高
    width = 100
    height = 25
    # 创建画布
    image = Image.new('RGB', (width, height), bgColor)
    # 构造字体对象
    # font = ImageFont.truetype('FreeMono.ttf', 24)
    font = ImageFont.load_default().font
    # 创建画笔
    draw = ImageDraw.Draw(image)
    # 创建文本内容
    text = '0123ABCD'
    # 逐个绘制字符
    textTemp = ''
    for i in range(4):
        textTemp1 = text[random.randrange(0, len(text))]
        textTemp += textTemp1
        draw.text((i * 25, 0),
                  textTemp1,
                  (255, 255, 255),
                  font)
    request.session['code'] = textTemp
    # 保存到内存流中
    # import cStringIO
    # buf = cStringIO.StringIO()
    # image.save(buf, 'png')

    # 内存文件操作-->此方法为python3的
    import io
    buf = io.BytesIO()
    # 将图片保存在内存中,文件类型为png
    image.save(buf, 'png')
    # 将内存流中的内容输出到客户端
    return HttpResponse(buf.getvalue(), 'image/png')


def verifyTest1(request):
    return render(request, 'booktest/verifyTest1.html')


def verifyTest2(request):
    code1 = request.POST['code1']
    code2 = request.session['code']
    if code1 == code2:
        return HttpResponse("ok")
    else:
        return HttpResponse("no")


def verifyCode_方式1(request):
    from PIL import Image, ImageDraw, ImageFont
    # 引入随机函数模块
    import random
    # 定义变量,用于画面的背景色、宽、高
    bgcolor = (random.randrange(20, 100), random.randrange(
        20, 100), 255)
    width = 100
    height = 25
    # 创建画面对象
    im = Image.new('RGB', (width, height), bgcolor)
    # 创建画笔对象
    draw = ImageDraw.Draw(im)
    # 调用画笔的point()函数绘制噪点
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        draw.point(xy, fill=fill)
    # 定义验证码的备选值
    str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
    # 随机选取4个值作为验证码
    rand_str = ''
    for i in range(0, 4):
        rand_str += str1[random.randrange(0, len(str1))]
    # 构造字体对象,ubuntu的字体路径为“/usr/share/fonts/truetype/freefont”
    # font = ImageFont.truetype('FreeMono.ttf', 23)
    font = ImageFont.load_default().font
    # 构造字体颜色
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
    # 绘制4个字
    draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
    draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
    draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
    draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
    # 释放画笔
    del draw
    # 存入session,用于做进一步验证
    request.session['verifycode'] = rand_str
    """
    python2的为
    # 内存文件操作
    import cStringIO
    buf = cStringIO.StringIO()
    """
    # 内存文件操作-->此方法为python3的
    import io
    buf = io.BytesIO()
    # 将图片保存在内存中,文件类型为png
    im.save(buf, 'png')
    # 将内存中的图片数据返回给客户端,MIME类型为图片png
    return HttpResponse(buf.getvalue(), 'image/png')

8.templates/booktest文件

verifyTest1

Django-html转义和csrf权限

1.创建app

python manage.py startapp booktest

2.setting添加booktest

3.配置跟目录的文件夹中的urls

from django.contrib import admin
from django.urls import path, re_path
from django.conf.urls import include

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'^captcha/', include('captcha.urls')),
    path('blog/', include('blog.urls')),
    # path('booktest/', include('booktest.urls', 'booktest')),
    # 2.0以后,反向解析使用以下方式
    path('booktest/', include(('booktest.urls', 'booktest'), namespace='booktest')),
]

4.配置booktest/urls

from django.urls import path, re_path
from . import views

urlpatterns = [
    re_path(r'^htmlTest$', views.htmlTest),
    re_path(r'^csrf1$', views.csrf1),
    re_path(r'^csrf2$', views.csrf2),

]

注:最新版本2.0以上使用path 或者re_path

 

5.编写视图

from django.shortcuts import render
from django.http import HttpResponse
from booktest.models import HeroInfo
import logging


# html转义
def htmlTest(request):
    context = {'t1': '<h1>123</h1>'}
    return render(request, 'booktest/htmlTest.html', context)


# csrf
def csrf1(request):
    return render(request, 'booktest/csrf1.html')


def csrf2(request):
    uname = request.POST['uname']
    return HttpResponse(uname)

6.templates/booktest文件

csrf1 htmlTest

Django-定于模板与模板继承

1.创建app

python manage.py startapp booktest

2.setting添加booktest

3.配置跟目录的文件夹中的urls

from django.contrib import admin
from django.urls import path, re_path
from django.conf.urls import include

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'^captcha/', include('captcha.urls')),
    path('blog/', include('blog.urls')),
    # path('booktest/', include('booktest.urls', 'booktest')),
    # 2.0以后,反向解析使用以下方式
    path('booktest/', include(('booktest.urls', 'booktest'), namespace='booktest')),
]

4.配置booktest/urls

from django.urls import path, re_path
from . import views

urlpatterns = [
    path('', views.index),
    re_path(r'^(\d+)/(\d+)$', views.show, name='show'),
    re_path(r'^index2$', views.index2, name='index2'),
    re_path(r'^user1', views.user1, name='user1'),
    re_path(r'^user2', views.user2, name='user2'),

]

注:最新版本2.0以上使用path 或者re_path

 

5.编写视图

from django.shortcuts import render
from django.http import HttpResponse
from booktest.models import HeroInfo
import logging


def index(request):
    # hero = HeroInfo.objects.get(pk=1)
    # context = {'hero': hero}

    # logging.debug('调试: %s' % (hero.hname))
    list = HeroInfo.objects.filter(isDelete=False)
    context = {'list': list}
    return render(request, 'booktest/index.html', context)


def show(request, id, id2):
    context = {'id': id}
    return render(request, 'booktest/show.html', context)


# 用于练习模板的继承
def index2(request):
    return render(request, 'booktest/index2.html')


def user1(request):
    context = {'uname': '习总'}
    return render(request, 'booktest/user1.html', context)


def user2(request):
    return render(request, 'booktest/user2.html')


6.templates/booktest文件

base base_goods base_user index index2 show user1 user2