You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django admin密码修改表单添加密码显隐按钮及调整输入框高度问询

完整修改后的模板代码

{% extends '../base.html' %}

{% block content %}
  <h2>修改密码</h2>
  <style>
    /* 调整输入框高度和基础样式 */
    input {
      height: 42px;
      padding: 0 12px;
      font-size: 16px;
      box-sizing: border-box;
      width: 320px;
    }
    /* 密码输入框容器相对定位,用于放置切换按钮 */
    .pwd-field-wrapper {
      position: relative;
      display: inline-block;
    }
    /* 显示/隐藏按钮样式 */
    .pwd-toggle-btn {
      position: absolute;
      right: 8px;
      top: 50%;
      transform: translateY(-50%);
      border: none;
      background: none;
      cursor: pointer;
      color: #666;
      font-size: 14px;
    }
  </style>
  <form method="post">
    {% csrf_token %}
    {% for field in form %}
      <p>
        {{ field.label_tag }}<br>
        {% if field.field.widget.input_type == 'password' %}
        <div class="pwd-field-wrapper">
          {{ field }}
          <button type="button" class="pwd-toggle-btn">显示</button>
        </div>
        {% else %}
        {{ field }}
        {% endif %}
        {% if field.help_text %}
          <small style="color: grey">{{ field.help_text }}</small>
        {% endif %}
        {% for error in field.errors %}
          <p style="color: red">{{ error }}</p>
        {% endfor %}
      </p>
    {% endfor %}
    <button type="submit">修改密码</button>
  </form>

  <script>
    // 绑定所有密码切换按钮的点击事件
    const toggleBtns = document.querySelectorAll('.pwd-toggle-btn')
    toggleBtns.forEach(btn => {
      btn.addEventListener('click', function() {
        const pwdInput = this.previousElementSibling
        if (pwdInput.type === 'password') {
          pwdInput.type = 'text'
          this.textContent = '隐藏'
        } else {
          pwdInput.type = 'password'
          this.textContent = '显示'
        }
      })
    })
  </script>
{% endblock %}

改动说明

  • 输入框高度调整:通过CSS统一设置输入框的高度、内边距和字号,你可以根据需求自行调整height属性的数值适配需要的尺寸
  • 显示/隐藏密码功能:通过判断字段类型自动给所有密码字段包裹容器、添加切换按钮,JS逻辑实现点击切换输入框的type属性,完成密码明文/密文的切换,不需要额外修改表单字段定义
  • 样式兼容:切换按钮采用透明背景设计,和原有Django admin的风格保持一致,不会出现突兀的视觉变化

内容的提问来源于stack exchange,提问作者Lutaaya Huzaifah Idris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 06:00:01