百年da孤独 2014-07-07
1、安装django-simple-captcha类库
pip install django-simple-captcha
2、增加captcha 到settings 下的 app字典中
3、创建数据库
python manage.py syncdb
4、增加URL配置到项目URL中
urlpatterns += patterns('', url(r'^captcha/', include('captcha.urls')), )
5、增加model
from django import forms from captcha.fields import CaptchaField class CaptchaForm(forms.Form): captcha = CaptchaField(label=u"验证码")
或
from django import forms from captcha.fields import CaptchaField class CaptchaTestModelForm(forms.ModelForm): captcha = CaptchaField() class Meta: model = MyModel
6、前端的展示以及验证
def register_page(request): ret = { 'captcha': CaptchaForm() } return render_to_response("accounts/new_register.html", ret)
{{ captcha }} {% if captcha_error %} <p style="color: red"> {{ captcha_error }}</p> {% endif %}
7、后台接受以及验证
form = CaptchaForm(request.POST) if form.is_valid(): pass else: ret['captcha_error'] = "验证码错误" success_flag = False ret['captcha'] = CaptchaForm()