Django-将Google Recaptcha v2添加到登录表单 [英] Django - adding google recaptcha v2 to login form

查看:154
本文介绍了Django-将Google Recaptcha v2添加到登录表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Recaptcha添加到Django的登录表单中。我尝试了不同的库,但它们似乎都不起作用,因为验证码表单没有出现在模板中。

I'm triying to add Recaptcha to my login form in Django. I tried different libraries but none of them seems to work, since the captcha form just doesn't appear in my template.

这是我当前的工作:

urls.py

path(r'captcha/', include('captcha.urls'))

forms.py

class NewUserForm(UserCreationForm):
    email = forms.EmailField(required=True)

    class YourForm(forms.Form):
        captcha = CaptchaField()

    class Meta:
        model = User
        fields = ("username", "email", "password1", "password2")

    def save(self, commit=True):
        user = super(NewUserForm, self).save(commit=False)
        user.email = self.cleaned_data['email']
        if commit:
            user.save()
        return user

这是我的 login.html 模板

<form action="/your-name/" method="post">
   {% csrf_token %}
   {{ form.captcha }}
   <input type="submit" value="Submit">
</form>

在这种情况下,只有 Submit 按钮会显示,但验证码不会出现。这就是我尝试过的任何其他库所发生的事情。谁能给我些帮助吗?

In this case, only the Submit button will appear, but not the captcha form. This is what happened with any other library I tried. Can anyone give me some help? Thanks in advance!

推荐答案

直接帮助很困难,因为您没有提到要使用的库。这是我在Django登录中添加v2验证码的方法,不需要其他库。

It's difficult to directly help as you did not mention what library you were trying to use. Here is my approach to adding a v2 recaptcha to Django login, no additional libs required.

在此示例中,我将recaptcha脚本添加到django登录模板,并覆盖django auth应用程序的登录视图,以扩展其功能以验证Recaptcha服务器端(根据 google docs )。

In this example, I add the recaptcha script to the django login template, and override django auth app's login view, in order to extend its functionality such that it validates the recaptcha server side (with the appropriate RECAPTCHA_SECRET as per google docs).

还要注意,context_processor用于在登录模板中插入RECAPTCHA_SITE_KEY。

Also note that context_processor is used to insert the RECAPTCHA_SITE_KEY in the login template.

登录.html

...
<head>
   <script src="https://www.google.com/recaptcha/api.js" async defer</script>
<script>
  function onSubmit(token) {
    document.getElementById("theForm").submit();
  }
</script>
</head>
<body>
<form id="theForm">
<button class="g-recaptcha btn btn-primary" 
        data-callback="onSubmit" 
        data-sitekey="{{RECAPTCHA_SITE_KEY}}" 
        type="submit">Login
</button>
</form>
</body>
...

url.py

...
# overriding auth app endpoint 
url(r'^accounts/login/', MyLoginView.as_view(), name='login'),
...

context_processor.py

from django.conf import settings 


def recaptcha_site_key(request):
    return {'RECAPTCHA_SITE_KEY': settings.RECAPTCHA_SITE_KEY}

settings.py

TEMPLATES = [
  {
    ...
    'OPTIONS': {
        'context_processors': [
            ...
            'yourapp.context_processors.recaptcha_site_key',
            ...
        ],
    },
  },
]

MyLoginView.py

from django.contrib.auth import views as auth_views

def _validate_recaptcha(token, ip):
    # implement server side validation according to google docs
    pass    

class MyLoginView(auth_views.LoginView):
'''Edited per @avib answer
'''
    def post(self, form):

        request_body = self.request.POST
        if not request_body:
            return None
    
        recaptcha_token = request_body['g-recaptcha-response']
        ip_addr, _ = get_client_ip(self.request)
        if not _validate_recaptcha(recaptcha_token, ip_addr):
            # your logic
            return redirect('login')

    return super().post(form)

这篇关于Django-将Google Recaptcha v2添加到登录表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆