我正在尝试在向导表单上实施Google reCaptcha v2。如果我填写了验证码并提交了表单而未填写其他字段,则返回结果:
{'success': True, 'challenge_ts': '2018-10-30T21:47:25Z', 'hostname': '127.0.0.1'}.
但是,如果我填写了所有必填字段,以便表格有效,则返回结果:
{'success': True, 'challenge_ts': '2018-10-30T21:47:25Z', 'hostname': '127.0.0.1'}.
{'success': False, 'error-codes': ['timeout-or-duplicate']}
[30/Oct/2018 21:47:44] "POST /register/ HTTP/1.1" 200 3912
使表格无效,并引发无效的验证码错误。我猜问题是验证码被两次验证了。我的验证验证码逻辑采用的是clean方法,因此可能是问题所在:
def clean(self):
cleaned_data = super(Form, self).clean()
recaptcha_response = self.request.POST.get('g-recaptcha-response')
url = 'https://www.google.com/recaptcha/api/siteverify'
values = {
'secret': settings.RECAPTCHA_SECRET_KEY,
'response': recaptcha_response
}
data = urllib.parse.urlencode(values).encode()
req = urllib.request.Request(url, data=data)
response = urllib.request.urlopen(req)
result = json.loads(response.read().decode())
print (result)
if result['success']:
return cleaned_data
else:
raise forms.ValidationError('Error.')
我想知道它是否与视图中的完成方法冲突:
def done(self, form_list, **kwargs):
data = {k: v for form in form_list for k, v in form.cleaned_data.items()}
关于如何解决此问题的任何想法?