gpt4 book ai didi

django表单向导和recaptcha

转载 作者:行者123 更新时间:2023-12-04 12:50:06 25 4
gpt4 key购买 nike

我使用以下 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 方法,即使验证码包含在最后一个表单中。

如下所示:
    from registration.forms import RegistrationWizard,RegistrationForm,ProfileForm

url(r'^register/$',
RegistrationWizard([RegistrationForm,ProfileForm]),
name='register_wizard'),

我该如何规避这种情况。什么需要在最后一个表单上调用 clean 两次?

最佳答案

如果一个表单被绑定(bind),它在渲染时总是会调用 clean(即使你不调用 form.is_valid)。

关于django表单向导和recaptcha,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1526399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com