Я хочу внедрить 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
https://medium.com/@mihfazhillah/how-to-implement-google-recaptcha-v3-on-your-django-app-3e4cc5b65013
Но не повезло, пытаясь понять это. Может кто-нибудь помочь мне?
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:"