pip install pillow
from PIL import Image, ImageDraw, ImageFont def get_code(request): img_obj = Image.new('RGB', (226, 34), get_rgb()) img_draw = ImageDraw.Draw(img_obj) img_font = ImageFont.truetype('static/font/333.ttf', 30) code = '' for i in range(5): upper_str = chr(random.randint(65, 90)) lower_str = chr(random.randint(97, 122)) num = random.randint(0, 9) res = random.choice([upper_str, lower_str, num]) img_draw.text((35 + i * 35, 0), res, get_rgb(), img_font) code += res io_obj = BytesIO() img_obj.save(io_obj, 'png') request.session['code'] = code return HttpResponse(io_obj.getvalue()) def get_rgb(): return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)