在 Django 中自定义管理表单,同时使用自动发现

问题描述

我想修改 Django 内置 django.contrib.auth 模块的一些小细节.具体来说,我想要一个不同的表单,使用户名成为电子邮件字段(并通过电子邮件发送备用电子邮件地址.(我宁愿不修改 auth 任何必要的 - 一个简单的表单更改 似乎 就是所有需要的.)

I want to modify a few tiny details of Django's built-in django.contrib.auth module. Specifically, I want a different form that makes username an email field (and email an alternate email address. (I'd rather not modify auth any more than necessary -- a simple form change seems to be all that's needed.)

当我将 autodiscoverauth 的自定义 ModelAdmin 一起使用时,我最终会与 auth 自己的冲突管理界面并收到已注册"错误.

When I use autodiscover with a customized ModelAdmin for auth I wind up conflicting with auth's own admin interface and get an "already registered" error.

看来我必须创建自己的管理站点,枚举我的所有模型.它只有 18 个类,但似乎是一个 DRY 问题——每次更改都需要添加到模型和添加到自定义管理站点.

It looks like I have to create my own admin site, enumerating all of my Models. It's only 18 classes, but it seems like a DRY problem -- every change requires both adding to the Model and adding to the customized admin site.

或者,我是否应该编写自己的autodiscover with excludes"版本来导入所有 admin 模块 except auth?

Or, should I write my own version of "autodiscover with exclusions" to essentially import all the admin modules except auth?


解决方案

以上都不是.只需使用 admin.site.unregister().这是我最近在管理中添加过滤用户 is_active 的方法(nb is_active 过滤现在默认在 Django 核心中的用户模型上;仍然作为示例在这里工作),所有 DRY 都可以:

None of the above. Just use admin.site.unregister(). Here's how I recently added filtering Users on is_active in the admin (n.b. is_active filtering is now on the User model by default in Django core; still works here as an example), all DRY as can be:

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User

class MyUserAdmin(UserAdmin):
    list_filter = UserAdmin.list_filter + ('is_active',)

admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)

相关文章