在项目中用到验证码,懒得去找,自己随便写了一个:
views.py:
def get_check_code_image(request,image='media/images/checkcode.gif'): import Image, ImageDraw, ImageFont, random im = Image.open(image) draw = ImageDraw.Draw(im) mp = md5.new() mp_src = mp.update(str(datetime.now())) mp_src = mp.hexdigest() rand_str = mp_src[0:4] draw.text((10,10), rand_str[0], font=ImageFont.truetype("ARIAL.TTF", random.randrange(25,50))) draw.text((48,10), rand_str[1], font=ImageFont.truetype("ARIAL.TTF", random.randrange(25,50))) draw.text((85,10), rand_str[2], font=ImageFont.truetype("ARIAL.TTF", random.randrange(25,50))) draw.text((120,10), rand_str[3], font=ImageFont.truetype("ARIAL.TTF", random.randrange(25,50))) del draw request.session['checkcode'] = rand_str buf = cStringIO.StringIO() im.save(buf, 'gif') return HttpResponse(buf.getvalue(),'image/gif')
urls.py:
from django.conf.urls.defaults import * urlpatterns = patterns('tracer_server.apps.user.views', # Uncomment this for admin: # (r'^admin/', include('django.contrib.admin.urls')), (r'^get_check_code_image/$', 'get_check_code_image'), )template:
<img onclick="this.setAttribute('src','/user/get_check_code_image/?nocache='+Math.random());" src="/user/get_check_code_image/" alt="CheckCode"/>