如何在Django中验证Captcha表单


如何在django中验证captcha表单?

forms.py:

from django import forms
from captcha import fields
class Cap(forms.Form):
cap=fields.CaptchaField()

视图中的模板渲染器功能:

def cap(request:HttpRequest):
return render(request,"cap.html",{"form":Cap})

模板:

<form action="" method="post">
{% csrf_token %}
{{form.cap}}
<button type="submit">Submit!</button>
</form>

视图中的form.is_valid()函数在哪里使用?

def clean(self):
cleaned_data = super().clean()
google_recaptcha_token = cleaned_data.get('g-recaptcha-response')
if not google_recaptcha_token:
raise ValidationError("Captcha Verficiation not submitted.")
recaptha_status = json.loads(
requests.post('https://www.google.com/recaptcha/api/siteverify',
data={
'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
'response': google_recaptcha_token}).text
)
if recaptha_status['success'] == False or recaptha_status['success'] < 0.5:
raise ValidationError("Captcha Verficiation failed.")

最新更新