本文介绍了django表单向导和recaptcha的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用以下进行recaptcha集成
I did a recaptcha integration using the following django snippet
settings.py
RECAPTCHA_PUBLIC_KEY = '<your public key>'
RECAPTCHA_PRIVATE_KEY = '<your private key>'
#widgets.py
from django import forms
from django.utils.safestring import mark_safe
from django.conf import settings
from recaptcha 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)]
#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 marcofucci_utils.widgets import ReCaptcha
from recaptcha 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]
#forms.py
class RegistrationForm(forms.Form):
...
recaptcha = marcofucci_fields.ReCaptchaField()
...
但是我已经定义了表单在django表单向导中,即使验证码包含在最后一个表单中,也会在该字段上调用clean方法。
But I have the forms defined in the django forms wizard and it calls the clean method on the field twice, even if the captcha is included in the last form.
如下所示:
from registration.forms import RegistrationWizard,RegistrationForm,ProfileForm
url(r'^register/$',
RegistrationWizard([RegistrationForm,ProfileForm]),
name='register_wizard'),
如何规避这种情况?在最后一个表单上调用clean的需要是两次?
How do I circumvent this situation. What is the need to call the clean on the last form twice?
推荐答案
如果一个表单被绑定,它会一直调用clean当渲染(即使你不调用form.is_valid)。
If a form is bound, it will allways call clean when renderering (even if you don't call form.is_valid).
这篇关于django表单向导和recaptcha的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!