Django - 覆盖管理站点的登录表单 [英] Django - Override admin site's login form

查看:34
本文介绍了Django - 覆盖管理站点的登录表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试在登录管理站点时覆盖 Django 1.4 中使用的默认表单(我的站点使用选择加入双因素身份验证的用户所需的额外令牌"字段,并且对于站点是强制性的职员).Django 的默认表单不支持我所需要的.目前,我的 templates/ 目录中有一个名为 templates/admin/login.html 的文件,它似乎正确地覆盖了与我使用的模板一起使用的模板在我的网站的其余部分.文件内容如下:

I'm currently trying to override the default form used in Django 1.4 when logging in to the admin site (my site uses an additional 'token' field required for users who opt in to Two Factor Authentication, and is mandatory for site staff). Django's default form does not support what I need. Currently, I've got a file in my templates/ directory called templates/admin/login.html, which seems to be correctly overriding the template used with the one I use throughout the rest of my site. The contents of the file are simply as below:

# admin/login.html:
{% extends "login.html" %}

实际登录表单如下:

# login.html:
{% load url from future %}<!DOCTYPE html>
<html>
    <head>
        <title>Please log in</title>
    </head>
    <body>
        <div id="loginform">
            <form method="post" action="{% url 'id.views.auth' %}">
                {% csrf_token %}
                <input type="hidden" name="next" value="{{ next }}" />
                {{ form.username.label_tag }}<br/>
                {{ form.username }}<br/>
                {{ form.password.label_tag }}<br/>
                {{ form.password }}<br/>
                {{ form.token.label_tag }}<br/>
                {{ form.token }}<br/>
                <input type="submit" value="Log In" />
           </form>
        </div>
    </body>
</html>

我的问题是,使用我的正常登录 URL 访问时,提供的表单工作得非常好,因为我提供自己的 AuthenticationForm 作为要显示的表单,但是通过 Django Admin 登录路由,Django 喜欢为这个模板提供它自己的表单,因此只有 usernamepassword 字段呈现.有什么办法可以使这项工作,还是我最好将 HTML 字段硬编码"到表单中?

My issue is that the form provided works perfectly fine when accessed using my normal login URLs because I supply my own AuthenticationForm as the form to display, but through the Django Admin login route, Django likes to supply it's own form to this template and thus only the username and password fields render. Is there any way I can make this work, or is this something I am just better off 'hard coding' the HTML fields into the form for?

推荐答案

AdminSite 有一个 login_form 属性,您可以使用它来覆盖所使用的表单.

AdminSite has a login_form attribute that you can use to override the form used.

Subclass AdminSite 然后使用您的子类的实例而不是 django.contrib.admin.site 在管理员、urls.py 等中注册您的模型.

Subclass AdminSite and then use an instance of your subclass instead of django.contrib.admin.site to register your models in the admin, in urls.py, etc.

所有内容都在文档中.

这篇关于Django - 覆盖管理站点的登录表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆