xadmin 登录页添加验证码

安装captcha

pip install django-simple-captcha

settings.py

INSTALLED_APPS = [
...
'captcha',
]

urls.py

urlpatterns = [
    path('xadmin/', xadmin.site.urls),
    path('captcha/', include("captcha.urls")),
    path('', include('www.urls')),
]

xadmin.forms.py

from captcha.fields import CaptchaField

class AdminAuthenticationForm(AuthenticationForm):
    """
    A custom authentication form used in the admin app.

    """
    # 添加这一行
    captcha = CaptchaField()
    
    this_is_the_login_form = forms.BooleanField(
        widget=forms.HiddenInput, initial=1,
        error_messages={'required': ugettext_lazy("Please log in again, because your session has expired.")})

xadmin.templates.views.login.html

<!-- 在两个input标签上面添加div -->
<div class="row" id="id_captcha_100">
  <div class="controls clearfix">
      <div class="input-group input-group-lg">
         {{ form.captcha }}
         {% for error in form.captcha.errors %}
           <p id="error_{{forloop.counter}}_{{field.auto_id}}" style="color:red" class="text-danger help-block">{{error}}</p>
         {% endfor %}
      </div>
  </div>
</div>
      

      <input type="hidden" name="this_is_the_login_form" value="1" />
      <input type="hidden" name="next" value="{{ next }}" />


<!-- 在最后添加js -->
<script type="text/javascript">

document.getElementById('id_username').focus()
$(function () {
    $("#id_captcha_1").addClass("form-control input-lg").css({"width": "200px", "display": "inline-block", "margin-left":"15px", "height": "40px"}).attr("placeholder", "请输入验证码");

    // 图片验证码点击刷新事件,以下是新增行
    $("#id_captcha_100 img").click(function () {
      $.get("/captcha/refresh/", function (data) {
        if (data.key != "") {
          $("#id_captcha_100 img").attr("src", data.image_url);
          $("#id_captcha_0").attr("value", data.key)
        }
      })
    })
})

document.getElementById('id_username').focus()
</script>
posted @ 2021-04-12 17:44  黄小墨  阅读(243)  评论(0编辑  收藏  举报