我想将Google Recaptcha v3实施为有效的Django联系人表单。
我尝试了以下这些教程:
https://simpleisbetterthancomplex.com/tutorial/2017/02/21/how-to-add-recaptcha-to-django-site.html
https://foxrow.com/using-recaptcha-v3-with-django
但是没有办法尝试解决这个问题。有人可以帮我吗?
Settings.py:
GOOGLE_RECAPTCHA_SECRET_KEY = '<KEY>'
HTML:
<script>
grecaptcha.ready(function() {
grecaptcha.execute('<SITE_KEY>', {action: 'contact'})
.then(function(token) {
document.getElementById("form").appendChild(document.CreateElement(`<input type="hidden" name="g-recaptcha-response" value=${token}`);
});
});
</script>
<form role="form" action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<script src='https://www.google.com/recaptcha/api.js?render=<SITE_KEY>'></script>
<div class="g-recaptcha" data-sitekey="<SITE_KEY>"></div>
<button type="submit">Submit</button>
</form>
Views.py:
def contact(request):
form_class = ContactForm
# new logic!
if request.method == 'POST':
form = form_class(data=request.POST)
if form.is_valid():
contact_name = request.POST.get(
'contact_name'
, '')
contact_email = request.POST.get(
'contact_email'
, '')
form_content = request.POST.get('content', '')
# Email the profile with the
# contact information
template = get_template('contact_template.txt')
context = {
'contact_name': contact_name,
'contact_email': contact_email,
'form_content': form_content,
}
content = template.render(context)
email = EmailMessage(
"New contact form submission",
content,
"Your website" +'',
['GMAIL_ADDRESS'],
headers = {'Reply-To': contact_email }
)
email.send()
messages.info(request, "Success")
return render(request, 'contact.html', {
'form': form_class,
})
Forms.py:
from django import forms
class ContactForm(forms.Form):
contact_name = forms.CharField(required=True)
contact_email = forms.EmailField(required=True)
content = forms.CharField(
required=True,
widget=forms.Textarea
)
# the new bit we're adding
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.fields['contact_name'].label = "Name:"
self.fields['contact_email'].label = "Email:"
self.fields['content'].label = "Message:"
答案 0 :(得分:1)
我今天遇到了同样的问题。 似乎JavaScript代码段不正确:
我通常不使用javascript编写代码,所以我不知道最佳实践,但这对我有用:
<script src='https://www.google.com/recaptcha/api.js?render=<KEY>'></script>
<script>
grecaptcha.ready(function() {
grecaptcha.execute(<KEY>, {action: 'contact'})
.then(function(token) {
ginput = document.createElement('input');
ginput.type = "hidden";
ginput.name = "g-recaptcha-response";
ginput.value = token;
document.getElementById("cform").appendChild(ginput);
});
});
</script>