• django-admin登录窗口添加验证码功能-(替换原有的login.html)captcha插件


    需求:
    1:更改django框架的admin登录窗口标题
    2:在admin登录窗口中添加验证码功能
    3:验证码允许点击更换
    步骤如下:
    1:安装插件以及在安装列表中添加插件
    2:自定义表单forms.py
    3:创建login.html文件(复制django内置的login.html文件进行更改)
    4:在admin.py文件中进行修改(编写登录窗口的信息)
    5:对主项目中的urls.py进行修改
    6:登录后台–需要验证码
    7:settings.py文件中设置验证码的大小和长度(自定义验证码的规格)

    B视频地址

    django-admin替换原来的login登录窗口并添加验证码验证功能

    1:安装插件以及在安装列表中添加插件

    pip install  django-simple-captcha
    
    • 1
    INSTALLED_APPS = [  
        # 使用多合一有点慢  
        # 'multi_captcha_admin',# 多合一验证码  
        'import_export', # 导出excel插件位置  
        'django.contrib.admin',  
        'django.contrib.auth',  
        'django.contrib.contenttypes',  
        'django.contrib.sessions',  
        'django.contrib.messages',  
        'django.contrib.staticfiles',  
        'app.apps.AppConfig',  
        'userprofile.apps.UserprofileConfig', # user表额外一对一表  
        'store.apps.StoreConfig',  
        'ownorder.apps.OwnorderConfig',  
        'outsourcing.apps.OutsourcingConfig',  
        'captcha',# 验证码  
    ]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    2:自定义表单

    在这里插入图片描述

    from django.contrib.auth.forms import AuthenticationForm  
    from captcha.fields import CaptchaField  
      
      
    class AppAuthenticationForm(AuthenticationForm):  
        captcha = CaptchaField()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    3:创建login.html文件

    在这里插入图片描述

    复制django包中自带的login.html文件中的代码到这里新建的login.html文件中

    django自带的login.html文件代码如下

    {% extends "admin/base_site.html" %}  
    {% load i18n static %}  
      
    {% block extrastyle %}{{ block.super }}<link rel="stylesheet" href="{% static "admin/css/login.css" %}">  
    {{ form.media }}  
    {% endblock %}  
      
    {% block bodyclass %}{{ block.super }} login{% endblock %}  
      
    {% block usertools %}{% endblock %}  
      
    {% block nav-global %}{% endblock %}  
      
    {% block nav-sidebar %}{% endblock %}  
      
    {% block content_title %}{% endblock %}  
      
    {% block nav-breadcrumbs %}{% endblock %}  
      
    {% block content %}  
    {% if form.errors and not form.non_field_errors %}  
    <p class="errornote">  
    {% blocktranslate count counter=form.errors.items|length %}Please correct the error below.{% plural %}Please correct the errors below.{% endblocktranslate %}  
    </p>  
    {% endif %}  
      
    {% if form.non_field_errors %}  
    {% for error in form.non_field_errors %}  
    <p class="errornote">  
        {{ error }}  
    </p>  
    {% endfor %}  
    {% endif %}  
      
    <div id="content-main">  
      
    {% if user.is_authenticated %}  
    <p class="errornote">  
    {% blocktranslate trimmed %}  
        You are authenticated as {{ username }}, but are not authorized to  
        access this page. Would you like to login to a different account?  
    {% endblocktranslate %}  
    </p>  
    {% endif %}  
      
    <form action="{{ app_path }}" method="post" id="login-form">{% csrf_token %}  
      <div class="form-row">  
        {{ form.username.errors }}  
        {{ form.username.label_tag }} {{ form.username }}  
      </div>  
      <div class="form-row">  
        {{ form.password.errors }}  
        {{ form.password.label_tag }} {{ form.password }}  
        <input type="hidden" name="next" value="{{ next }}">  
      </div>  {% url 'admin_password_reset' as password_reset_url %}  
      {% if password_reset_url %}  
      <div class="password-reset-link">  
        <a href="{{ password_reset_url }}">{% translate 'Forgotten your password or username?' %}</a>  
      </div>  {% endif %}  
      <div class="submit-row">  
        <input type="submit" value="{% translate 'Log in' %}">  
      </div></form>  
      
    </div>  
    {% endblock %}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65

    修改后
    添加验证码块
    并且添加点击验证码刷新的功能

    {% extends "admin/base_site.html" %}  
    {% load i18n static %}  
      
    {% block extrastyle %}{{ block.super }}<link rel="stylesheet" href="{% static "admin/css/login.css" %}">  
    {{ form.media }}  
    {% endblock %}  
      
    {% block bodyclass %}{{ block.super }} login{% endblock %}  
      
    {% block usertools %}{% endblock %}  
      
    {% block nav-global %}{% endblock %}  
      
    {% block nav-sidebar %}{% endblock %}  
      
    {% block content_title %}{% endblock %}  
      
    {% block nav-breadcrumbs %}{% endblock %}  
      
    {% block content %}  
    {% if form.errors and not form.non_field_errors %}  
    <p class="errornote">  
    {% blocktranslate count counter=form.errors.items|length %}Please correct the error below.{% plural %}Please correct the errors below.{% endblocktranslate %}  
    </p>  
    {% endif %}  
      
    {% if form.non_field_errors %}  
    {% for error in form.non_field_errors %}  
    <p class="errornote">  
        {{ error }}  
    </p>  
    {% endfor %}  
    {% endif %}  
      
    <div id="content-main">  
      
    {% if user.is_authenticated %}  
    <p class="errornote">  
    {% blocktranslate trimmed %}  
        You are authenticated as {{ username }}, but are not authorized to  
        access this page. Would you like to login to a different account?  
    {% endblocktranslate %}  
    </p>  
    {% endif %}  
      
    <form action="{{ app_path }}" method="post" id="login-form">{% csrf_token %}  
      <div class="form-row">  
        {{ form.username.errors }}  
        {{ form.username.label_tag }} {{ form.username }}  
      </div>  
      <div class="form-row">  
        {{ form.password.errors }}  
        {{ form.password.label_tag }} {{ form.password }}  
        <input type="hidden" name="next" value="{{ next }}">  
      </div>  <div class="form-row">  
        {{ form.captcha.errors }}  
        {{ form.captcha.label_tag }} {{ form.captcha }}  
        <input type="hidden" name="next" value="{{ next }}">  
      </div>  {% url 'admin_password_reset' as password_reset_url %}  
      {% if password_reset_url %}  
      <div class="password-reset-link">  
        <a href="{{ password_reset_url }}">{% translate 'Forgotten your password or username?' %}</a>  
      </div>  {% endif %}  
      <div class="submit-row">  
        <input type="submit" value="{% translate 'Log in' %}">  
      </div>{#添加点击验证码刷新功能#}  
        <script src="{% static '/admin/huadong/jquery-3.6.0.min.js' %}"></script>  
        <script>        $('img.captcha').attr("title", "点击更换验证码");  
            $('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;        });  
        </script>  
      
    </form>  
      
    </div>  
    {% endblock %}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    验证码刷新功能使用到了jquery.js 我把这个放置到了本地,请自行更换其他版本
    
    • 1

    4在admin.py文件中进行修改
    在这里插入图片描述

    添加以下代码

    # forms中定义的表单 添加了验证码字段  
    from .forms import AppAuthenticationForm  
      
    class MyAdminSite(admin.AdminSite):  
        # 向django 自带的admin 中使用 自定义的表单  
        login_form = AppAuthenticationForm  
        # 自定义表单的位置  
        login_template = "app/login.html"  
        # 设置后台登陆显示标题--方法1  
        # 登录窗口所使用的显示标头以及网站标题  
        # 浏览器网站窗口显示文字  
        site_title = '业务管理系统'  
        # 登录窗口显示标题文字  
        site_header = '业务管理系统登录'  
        # index_title = '业务管理系统网页标题3'  
        # 添加打开这个管理后台显示的网站标题----窗口标题信息  
        admin.site.site_title = '业务管理系统网页标题'  
        # 添加打开这个管理后台显示的登录窗口网站标题  
        admin.site.site_header = '业务管理系统'  
      
    admin_site = MyAdminSite(name="management")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    admin_site
    对 AdminSite 类进行了子分类,以便我们可以随意修改和覆盖 django 默认管理员的任何模板,而不会影响默认管理员的任何内容,并继承 admin 的所有函数和模板
    
    • 1
    • 2

    5对主项目中的urls.py进行修改

    在这里插入图片描述

    from django.contrib import admin  
    from django.urls import path, include  
      
    # 添加自定义的登录  
    from app.admin import AppAuthenticationForm  
      
    admin.site.login_form = AppAuthenticationForm  
    admin.site.login_template = "app/login.html"  
      
    # admin.autodiscover()  
    # 在 Django 中,是一个函数,用于自动发现和注册 Django 项目中所有已安装应用的管理配置。此函数通常在项目的urls.py文件中调用。  
      
    urlpatterns = [  
        path('admin/', admin.site.urls),  
        path('captcha/', include('captcha.urls')),  
    ]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    6登录后台–需要验证码

    http://127.0.0.1:8000/admin/login/?next=/admin/
    
    • 1

    在这里插入图片描述

    7:settings.py文件中设置验证码的大小和长度

    # Font size of the captcha text
    CAPTCHA_FONT_SIZE = 40
    
    # Length of the captcha text (number of characters)
    CAPTCHA_LENGTH = 12
    
    # Number of attempts a user can try before captcha protection is enforced
    CAPTCHA_MAX_ATTEMPTS = 3
    
    # Timeout (in minutes) after which the captcha session expires
    CAPTCHA_TIMEOUT = 5
    
    # Image dimensions of the captcha image
    CAPTCHA_IMAGE_SIZE = (200, 100)
    
    # Custom image size for captcha (tuple of width and height)
    # If set, overrides CAPTCHA_IMAGE_SIZE
    # CAPTCHA_IMAGE_SIZE = (width, height)
    
    # Length of the generated audio captcha
    CAPTCHA_AUDIO_LENGTH = 5
    
    # Case sensitivity of the captcha text
    CAPTCHA_CASE_SENSITIVE = False
    
    # Characters allowed in the captcha text
    CAPTCHA_ALLOWED_CHARS = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'
    
    # Timeout for the cache (in seconds) for storing captcha
    CAPTCHA_TIMEOUT = 5 * 60  # 5 minutes
    
    # Directory where temporary captcha images/audio are stored
    CAPTCHA_OUTPUT_FORMAT = '%(time)s%(part)s.png'
    CAPTCHA_IMAGE_DIR = 'captcha'
    
    # Custom directory for storing captcha images/audio
    # CAPTCHA_IMAGE_DIR = 'custom_captcha_dir'
    
    # Timeout for the cache (in seconds) for storing captcha
    CAPTCHA_TIMEOUT = 5 * 60  # 5 minutes
    
    # Number of seconds for which the captcha cookie is valid
    CAPTCHA_COOKIE_TIMEOUT = CAPTCHA_TIMEOUT
    
    # Length of the hash used for storing the captcha image/audio in the cache
    CAPTCHA_CACHE_KEY_LENGTH = 16
    
    # The challenge text for the captcha audio
    CAPTCHA_CHALLENGE_FUNCT = 'captcha.helpers.math_challenge'
    
    # Function to generate captcha audio
    CAPTCHA_AUDIO_CHALLENGE_FUNCT = 'captcha.helpers.math_audio_challenge'
    
    # Custom challenge function for captcha text
    # CAPTCHA_CHALLENGE_FUNCT = 'myapp.utils.my_challenge_function'
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    Now that I've added the following code to my [django] project, please check it for me, please say what is added and what is missing, and where is it used?
    froms.py code:
    from django.contrib.auth.forms import AuthenticationForm  
    from captcha.fields import CaptchaField  
      
      
    class AppAuthenticationForm(AuthenticationForm):  
        captcha = CaptchaField()
    
    admin.py code:
    from django.contrib import admin  
      
    
    from .forms import AppAuthenticationForm  
      
    class MyAdminSite(admin.AdminSite):  
        login_form = AppAuthenticationForm  
        login_template = "weidanyewu/login.html"  
        site_title = 'sy'  
        site_header = 'sy'  
        admin.site.site_title = 'sy'  
        admin.site.site_header = 'sy'  
    admin_site = MyAdminSite(name="management")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
  • 相关阅读:
    Docker推送镜像错误
    [附源码]java毕业设计企业记账系统
    SQL Server数据库语法篇(终篇)
    metinfo 6.0.0任意文件读取漏洞复现
    音视频发展调研
    【STM32】时钟设置函数(寄存器版)
    在eclipse中配置weblogic12c1.1.0
    计算机毕业设计SSM大学生网上书店【附源码数据库】
    前后端交互:axios 和 json;springboot 和 vue
    CSGO饰品持续跌价,市场真的要崩盘了吗?
  • 原文地址:https://blog.csdn.net/weixin_47021806/article/details/136356678