`
zhouxi2010
  • 浏览: 50976 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

django添加验证码

阅读更多

1.安装recaptcha,命令:apt-get install  python-recaptcha

2.到https://www.google.com/recaptcha/admin/create去注册,获得public-key,private-key

3.在settings.py中添加:

RECAPTCHA_PUBLIC_KEY = '*public-key*'
RECAPTCHA_PRIVATE_KEY = '*private-key*'

4.在项目根目录下新建recaptchawidget文件夹, 并新建__init__.py,fields.pywidgets.py3个文件

5.编辑widgets.py:

from django import forms
from django.utils.safestring import mark_safe
from django.conf import settings
from recaptcha.client import captcha
    
class ReCaptcha(forms.widgets.Widget):
        recaptcha_challenge_name = 'recaptcha_challenge_field'
        recaptcha_response_name = 'recaptcha_response_field'
    
        def render(self, name, value, attrs=None):
            return mark_safe(u'%s' % captcha.displayhtml(settings.RECAPTCHA_PUBLIC_KEY))
    
        def value_from_datadict(self, data, files, name):
            return [data.get(self.recaptcha_challenge_name, None), 
                data.get(self.recaptcha_response_name, None)] 

 6.编辑fields.py:

from django.conf import settings
from django import forms
from django.utils.encoding import smart_unicode
from django.utils.translation import ugettext_lazy as _

from recaptchawidget.widgets import ReCaptcha
from recaptcha.client import captcha
    
class ReCaptchaField(forms.CharField):
        default_error_messages = {
            'captcha_invalid': _(u'Invalid captcha')
        }
    
        def __init__(self, *args, **kwargs):
            self.widget = ReCaptcha
            self.required = True
            super(ReCaptchaField, self).__init__(*args, **kwargs)
    
        def clean(self, values):
            super(ReCaptchaField, self).clean(values[1])
            recaptcha_challenge_value = smart_unicode(values[0])
            recaptcha_response_value = smart_unicode(values[1])
            check_captcha = captcha.submit(recaptcha_challenge_value, 
                recaptcha_response_value, settings.RECAPTCHA_PRIVATE_KEY, {})
            if not check_captcha.is_valid:
                raise forms.util.ValidationError(self.error_messages['captcha_invalid'])
            return values[0] 
 

这样便可以在app中使用了,具体参考http://www.rkblog.rk.edu.pl/w/p/recaptach-django-forms/

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics