前言
Action插件在數據列表頁面上提供數據選擇功能。可以在Action之后專門處理所選數據。批量刪除功能作為默認操作提供。
action文檔
要啟用Action,開發人員可以設置Model OptionClass的屬性“actions”,這是一種列表類型。xadmin官方文檔地址https://xadmin.readthedocs.io/en/latest/plugins.html
默認情況下,xadmin已啟用DeleteSelectedAction,它提供了從列表視圖中刪除所選項目的選項。您還可以實現自定義的Action類,請參閱以下示例。
首先需要一個Action類,它是BaseActionView的子類。BaseActionView是以下的子類ModelAdminView:
from xadmin.plugins.actions import BaseActionView
class MyAction(BaseActionView):
action_name = "my_action" #: 相當於這個 Action 的唯一標示, 盡量用比較針對性的名字
description = _(u'Test selected %(verbose_name_plural)s') #: 描述, 出現在 Action 菜單中, 可以使用 ``%(verbose_name_plural)s`` 代替 Model 的名字.
model_perm = 'change' #: 該 Action 所需權限
# 而后實現 do_action 方法
def do_action(self, queryset):
# queryset 是包含了已經選擇的數據的 queryset
for obj in queryset:
# obj 的操作
...
# 返回 HttpResponse
return HttpResponse(...)
然后在Model中的OptionClass上應用此Action
class MyModelAdmin(object):
actions = [MyAction, ]
案例操作
接下來有個需求:在Student列表頁,我需要勾選不同的項,實現清空學生成績的操作
在adminx.py同一目錄新建一個adminx_actions.py文件
- action_name 這個Action的唯一標示
- description 出現在 Action 菜單中名稱
- model_perm 該 Action 所需權限, 總共四種(‘add', 'change', 'delete', 'view‘)
- icon 顯示圖標
- do_action 執行的動作
# adminx_actions.py
from django.http import HttpResponse
from xadmin.plugins.actions import BaseActionView
class ClearAction(BaseActionView):
'''清空action'''
action_name = "clear_score" # 相當於這個Action的唯一標示, 盡量用比較針對性的名字
description = u'清空成績 %(verbose_name_plural)s' # 出現在 Action 菜單中名稱
model_perm = 'change' # 該 Action 所需權限
icon = 'fa fa-bug'
# 執行的動作
def do_action(self, queryset):
for obj in queryset:
# 需執行model對應的字段
obj.score = '0' # 重置score為0
obj.save()
# return HttpResponse
return None # 返回的url地址
接下來在adminx.py注冊表的時候添加一項actions=[ClearAction,]
# adminx.py
import xadmin
from .models import Student
from .xadmin_action import ClearAction
class ControlStudent(object):
# 顯示的字段
list_display = ['student_id', 'name', 'age', 'score',]
# 搜索條件
search_fields = ('name',)
# 每頁顯示10條
list_per_page = 10
actions = [ClearAction, ]
xadmin.site.register(Student, ControlStudent)
實現效果
打開學生表列表頁,勾選需要清除的行,左下角執行動作里面有個“清除成績的選項”
點擊后頁面會自動刷新,成績變成0