我正在使用 Django 注册包。我已经成功实现了 Django-reCAPTCHA 包。每次登录时都会出现验证码。
现在我希望验证码仅在 3 次登录尝试失败后才出现。我怎样才能实现它?
感谢任何帮助。谢谢。
最佳答案
首先将 session 中登录尝试失败的次数存储在登录 View 中: 使用此站点在 django 中实现 reCaptcha https://simpleisbetterthancomplex.com/tutorial/2017/02/21/how-to-add-recaptcha-to-django-site.html View .py
class UserLoginFormView(FormView):
form_class = LoginForm
success_url = reverse_lazy('appuser:test')
template_name = "appuser/login.html"
def dispatch(self, request, *args, **kwargs):
if ('lReq' in self.request.session):
request.session['lReq'] +=1
else:
request.session['lReq'] = 1
return super(UserLoginFormView,self).dispatch(request, *args, **kwargs)
在表单有效时根据 session 值做出决定
def form_valid(self,form):
if( self.request.session['lReq'] > 3):
..... your code to validate the captcha you will find in the site above...
def render_to_response(self, context, **response_kwargs):
if( self.request.session['lReq'] > 3):
context['cap'] = True
else:
context['cap'] = False
return super( UserLoginFormView,self).render_to_response(context,**response_kwargs)
在您的模板中
{% block content %}
<form method="post">
{% csrf_token %}
{{ form.as_p }}
{%if cap%}
<script src='https://www.google.com/recaptcha/api.js'></script>
<div class="g-recaptcha" data-sitekey="6LdRSRYUAAAAAFCqQ1aZnYfRGJIlAUMX3qkUWlcF"></div>
{%endif%}
<button type="submit" class="btn btn-primary">Post</button>
{% endblock %}
这应该有效
关于python - Django - 实现在 3 次登录尝试失败时显示 CAPTCHA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31018552/