django☞验证码

阅读量: zyh 2020-03-07 13:33:44
Categories: > Tags:

前言

高级主题 — Django Simple Captcha 0.5.14 文档 (django-simple-captcha.readthedocs.io)

安装

pip install django-simple-captcha

settings.INSTALLED_APPS加入captcha

配置

settings.py末尾中加入以下代码:

# 验证码设置
CAPTCHA_FIELD_TEMPLATE = "captcha/field.html" # 字段排列
CAPTCHA_TEXT_FIELD_TEMPLATE = "captcha/text_field.html" # 文本输入框
#CAPTCHA_HIDDEN_FIELD_TEMPLATE = "captcha/hidden_field.html" 
CAPTCHA_IMAGE_TEMPLATE = "captcha/image.html" # 验证码图标框
CAPTCHA_CHALLENGE_FUNCT = 'captcha.helpers.random_char_challenge' # 验证码类型
CAPTCHA_IMAGE_SIZE=(100,36) # 验证码尺寸
CAPTCHA_TIMEOUT=1
#CAPTCHA_OUTPUT_FORMAT=u'%(text_field)s %(hidden_field)s %(image)s'

具体

app:login为例,在其根目录构建以下内容

  1. 构建templates/captcha目录,并创建field.htmltext_field.htmlimage.html模板
❯ cat field.html
{{ text_field }}{{ hidden_field }}{{ image }}

❯ cat text_field.html
<input id="id_{{ name }}_1" name="{{ name }}_1" type="text" placeholder="captcha" />

❯ cat image.html
<img src="{{ image }}" alt="{{ name }}" class="{{ name }}"/>
  1. 构建static/login/js目录,并创建captcha.js,用于动态刷新验证码
❯ cat captcha.js
$('img.captcha').click(function() {
  $.getJSON('/captcha/refresh/',function(json) { // This should update your captcha image src and captcha hidden input
      console.log(json);
      $("img.captcha").attr("src",json.image_url);
      $("#id_captcha_0").val(json.key);
    });
    return false;
});
  1. 创建form表单调用captcha
❯ cat forms.py
"""
导入表单模块
"""
from django import forms
from captcha.fields import CaptchaField, CaptchaTextInput


class UserForm(forms.Form):
    """
    用户表单
    """
    username = forms.CharField(label='用户名', max_length=128, widget=forms.TextInput(attrs={'class': 'form-control'}))
    password = forms.CharField(label='密码', max_length=256, widget=forms.PasswordInput(attrs={'class': 'form-control'}))
    captcha = CaptchaField(label='验证码')
  1. 构建templates/login目录,并创建login.html模板调用caphtcha
{% load static %}
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- 上述meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
    <!-- Bootstrap CSS -->
    <link href="{% static 'login/css/login.css' %}" rel="stylesheet" />
    <link href="{% static 'fontawesome_free/css/all.min.css' %}" rel="stylesheet" type="text/css">
    <title>登录</title>
  </head>
  <body>
    <div id="container">
      <h1>登录</h1>
      {% if login_form.captcha.errors %}
        {% for error in login_form.captcha.errors %}
        😢😢😢{{ error }}😢😢😢
        {% endfor %}
      {% elif message %}
        😢😢😢{{ message }}😢😢😢
      {% else %}
        😊😊😊欢迎您的到来😊😊😊
      {% endif %}
      <form class="form" action="/login/" method="post">{% csrf_token %}
        <!-- 判断用户输入信息,并返回错误信息 -->
        {% for item in login_form %}
          {% if item.html_name == "username" %}
          
{% for error in item.errors %} {{ error }} {% endfor %} </text> </div> {% endif %} {% if item.html_name == "password" %}
{% for error in item.errors %} {{ error }} {% endfor %}
{% endif %} {% if item.html_name == "captcha" %}
{{ login_form.captcha }}
{% endif %} {% endfor %} <div class="item1"> <button type="submit">Go~~~~</button> <a href="/register/">Register</a> </div> </form> </div> <script src="https://cdn.bootcss.com/jquery/3.5.1/jquery.js"></script> <script src="https://cdn.bootcss.com/popper.js/1.16.0/umd/popper.js"></script> <script src="https://cdn.bootcss.com/twitter-bootstrap/4.5.3/js/bootstrap.min.js"></script> <script src="{% static 'login/js/captcha.js' %}"></script> </body> </html>
  1. 构建static/login/css目录,并创建login.css
❯ cat login.css
body {
background: url('../image/backend.jpg') center center no-repeat;
background-attachment: fixed;
background-size: cover;
}

input::-webkit-input-placeholder{
    color:#000000;
}
input::-moz-placeholder{   /* Mozilla Firefox 19+ */
    color:#000000;
}
input:-moz-placeholder{    /* Mozilla Firefox 4 to 18 */
    color:#000000;
}
input:-ms-input-placeholder{  /* Internet Explorer 10-11 */
    color:#000000;
}

#container {
    width: 35%;
    height: 400px;
    margin: 0 auto;
    margin-top: 15%;
    padding: 20px 50px;
    text-align: center;
    background: #ffffff50;
}
#container .alert {
    margin: 0 auto;
    width: 350px;
    text-align: left;
}

#container .form {
    margin-top: 30px;
}

#container .form .item {
    margin-top: 15px;
    position: relative;
}

#container .form .item i {
    font-size: 20px;
}
#container .form .item input {
    border: 0;
    border-bottom: 2px solid #000;
    padding: 10px 30px;
    background: #ffffff00;
    font-size: 20px;
    padding-left: 11px;
}


#container .form .item text {
    position: absolute;
    text-size: 5px;
    text-align: left;
    padding-top: 10px;
}

#container .form .item img {
    position: absolute;
}

#container .form .item1 {
    display: flex;
    justify-content: space-between;
    margin-top: 15px;
    padding-top: 5%;
    padding-left: 22%;
    padding-right: 22%;
}

#container .form .item1 button {
    width: 180px;
    height: 30px;
    font-size: 20px;
    font-weight: 600;
    color: #ffffff;
    background-image: linear-gradient(60deg, #64b3f4 0%, #c2e59c 100%);
    border-radius: 15px;
    border: 0;
}
#container .form .item1 a {
    text-decoration:none;
    width: 100px;
    font-size: 20px;
    font-weight: 600;
    color: #ffffff;
    background-image: linear-gradient(60deg, #64b3f4 0%, #c2e59c 100%);
    border-radius: 15px;
    border: 0;
}
  1. 添加路由

项目.urls.urlpatterns中添加path('captcha/', include('captcha.urls')),