简体   繁体   English

Django 管理员登录表

[英]Django Admin Login Form

How do I change the login form used by django admin (want to add a captcha field)?如何更改 django 管理员使用的登录表单(要添加验证码字段)? I am using the cookiecutter template and have followed the suggestions in other SO answers, and guides:我正在使用cookiecutter模板并遵循了其他 SO 答案和指南中的建议:

forms.py forms.py

class AuthAdminForm(AuthenticationForm):
    captcha = ReCaptchaField(widget=ReCaptchaV3)
    show_something_different = forms.TextInput()

    class Meta(AuthenticationForm):
        fields = ('email', 'password', 'show_something_different', 'captcha')   

urls.py网址.py

from django.contrib import admin
from myapp.forms import AuthAdminForm
admin.autodiscover()
admin.site.login_form = AuthAdminForm
admin.site.login_template = 'admin/login.html'
urlpatterns = [
    # Django Admin, use {% url 'admin:index' %}
   path(settings.ADMIN_URL, admin.site.urls),
   ...]

I was able to add admin/login.html to my templates dir and extend it.我能够将 admin/login.html 添加到我的模板目录并扩展它。 This works to add the google js to the header (can see it in source).这可以将 google js 添加到 header(可以在源代码中看到)。 But the captcha field and my dummy extra field don't show up.但是验证码字段和我的虚拟额外字段没有出现。

I was on the right track, but what caught me out is that the login.html template doesn't render every field present in the form (this is why my dummy test field never showed up).我走在正确的轨道上,但让我吃惊的是 login.html 模板并没有呈现表单中存在的每个字段(这就是为什么我的虚拟测试字段从未出现过)。 So instead of extending login.html, I copied the entire contents to my own file in templates/admin/login.html, then added the captcha field manually:因此,我没有扩展 login.html,而是将全部内容复制到我自己的 templates/admin/login.html 文件中,然后手动添加验证码字段:

<form action="{{ app_path }}" method="post" id="login-form">{% csrf_token %}
  <div class="form-row">
    {{ form.captcha }}
    {{ form.username.errors }}
    {{ form.username.label_tag }} {{ form.username }}
  </div>

base.html can be extended like this: base.html 可以这样扩展:

{% block extrahead %}
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-xxx"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
      gtag('config', 'G-xxx');
    </script>
{% endblock %}

Now, finally, captcha is on my admin login page.现在,验证码终于出现在我的管理员登录页面上了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM