• 参考资料
  • 练习题
  • 交流讨论

django做了登录页面,验证码后台打印出5位,可是页面只显示1位是什么原因?

酷数据 2021-09-11 21:49:02

页面显示只一位:

urls.py页:

from django.contrib import admin
from django.urls import path
from home import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
     path('login/', views.login_view, name='login'),
     path('get_valid_code_img/', views.get_valid_code_img_view),
]
if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL,
                          document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL,
                          document_root=settings.MEDIA_ROOT)

view.py页面:

from django.http import HttpResponse
import random
from django.shortcuts import render
from io import BytesIO  # 内存管理
from PIL import Image, ImageDraw, ImageFont


def login_view(request,):
    return render(request, 'login.html')


def get_valid_code_img_view(request):

    def get_random_color():
        return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
    img = Image.new("RGB", (250, 40), color=get_random_color())
    draw = ImageDraw.Draw(img)
    did_font = ImageFont.truetype("static/font/did.otf", size=30)
    for i in range(5):
        random_num = str(random.randint(0, 9))
        random_low_alpha = chr(random.randint(95, 122))
        random_upper_alpha = chr(random.randint(65, 90))
        random_char = random.choice([random_num, random_low_alpha, random_upper_alpha])

    draw.text((i*20+20, 5), random_char, get_random_color(), font=did_font)
    f = BytesIO()
    img.save(f, "png")
    data = f.getvalue()
    return HttpResponse(data)
...全文
3 点赞 收藏 回复
写回复
回复
切换为时间正序
请发表友善的回复…
发表回复

还没有回复,快来抢沙发~

发帖
Django
创建于2021-09-10

2

社区成员

帖子事件
创建了帖子
2021-09-11 21:49
社区公告
暂无公告