python 在 Django 中自定义管理表单,同时使用自动发现
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/471550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Customizing an Admin form in Django while also using autodiscover
提问by S.Lott
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 seemsto be all that's needed.)
我想修改 Django 内置django.contrib.auth
模块的一些小细节。具体来说,我想要一个不同的表单,使用户名成为一个电子邮件字段(并通过电子邮件发送一个备用电子邮件地址。(我宁愿不做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.
当我使用autodiscover
定制的ModelAdmin
for 时,auth
我最终会与auth
自己的管理界面发生冲突,并出现“已注册”错误。
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 andadding to the customized admin site.
看起来我必须创建自己的管理站点,枚举我的所有模型。它只有 18 个类,但这似乎是一个枯燥的问题——每次更改都需要添加到模型和添加到自定义管理站点。
Or, should I write my own version of "autodiscover
with exclusions" to essentially import all the admin
modules exceptauth
?
或者,我是否应该编写自己的“autodiscover
带排除项”版本来基本上导入除 之外的所有admin
模块?auth
回答by Carl Meyer
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:
以上都不是。只需使用 admin.site.unregister()。这是我最近在 admin 中在 is_active 上添加过滤用户的方法(nbis_active 过滤现在默认在 Django 核心的用户模型上;作为示例仍然在这里工作),所有 DRY 都可以:
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)
回答by Andy Baker
I think it might be easier to do this with a custom auth backend and thus remove the need for a customized ModelAdmin.
我认为使用自定义身份验证后端可能更容易做到这一点,从而消除对自定义 ModelAdmin 的需要。
I did something similar with this snippet: http://www.djangosnippets.org/snippets/74/
我对这个片段做了类似的事情:http: //www.djangosnippets.org/snippets/74/