带有Google Recaptcha v3的Django联系表

时间:2019-10-20 17:22:03

标签: javascript html django python-3.x recaptcha-v3

我想将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:"

1 个答案:

答案 0 :(得分:1)

我今天遇到了同样的问题。 似乎JavaScript代码段不正确:

  1. 您的元素需要一个ID。 (我的现在是“ cform”。)
  2. CreateElement不存在,“ c”为小写。
  3. 我无法创建具有属性的元素,因此必须分几个步骤进行。

我通常不使用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>