Adding custom action to UserModel's Admin page

可紊 提交于 2021-02-07 06:39:11

问题


Is there any possibility to create custom action in admin page for django UserModel? I want automatize adding user to group (like adding him to staff, set some extra values, etc.), and of course create actions that take these changes back.

Thanks for your help.


回答1:


Import User in your admin.py unregister it, create new ModelAdmin for it (or subclass the default one) and go wild.

It would look something like this I guess:

from django.contrib.auth.models import User

class UserAdmin(admin.ModelAdmin):
    actions = ['some_action']

    def some_action(self, request, queryset):
        #do something ...
    some_action.short_description = "blabla"

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

Reference for actions.




回答2:


Working example without losing all default inline actions etc.
Here we will add action which activates selected users.

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


def make_active(modeladmin, news, queryset):
    queryset.update(is_active=True)
make_active.short_description = u"Activate selected Users"

class CustomUserAdmin(UserAdmin):
    actions = [make_active]


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


来源:https://stackoverflow.com/questions/3652287/adding-custom-action-to-usermodels-admin-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!