Django Admin自定义按钮取消强制选择对象

当创建自定义按钮,点击时默认至少需要选择一个选项。若要取消该选择,当只使用django原生admin的时候只需要重写changelist_view即可,而若使用了其他组件如simpleui时,则还需要修改其他东西。本文记录在使用了simpleui的情况下,如何取消点击自定义按钮时的强制选择。

1. 默认情况下创建自定义按钮如下

2. 修改simpleui的actions.html

路径如下:
\venv\Lib\site-packages\simpleui\templates\admin\actions.html
来到第413行,可能因simpleui版本不同而具体行数不一样,添加修改后如下:

这里只是加了一个判断,自定义按钮的名字以fc_开头的话则直接调用点击事件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//TODO 需要做国际化
if (data_name.substr(0, 3) == "fc_") {
// 强制运行,不用选择数据,按钮名data_name必须以"fc_"开头
done.call(this)
} else if (checkbox_checked == 0 && data_name != "add_item" && !_action.customButton[data_name].action_url) {
_vue.$alert(getLanuage("Please select at least one option!"), '', {
type: 'warning'
})
} else if (confirm) {
_vue.$confirm(confirm, '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => done.call(this));

} else {
done.call(this)
}

3. 重写changelist_view方法

首先按钮定义如下,为一个简单的跳转操作,需要注意新增了一个动态属性acts_on_all

1
2
3
4
5
def fc_prev(self, request, queryset):
return HttpResponseRedirect("/admin/data/querytask/")
fc_prev.short_description = "返回查询任务页"
fc_prev.type = "primary"
fc_prev.acts_on_all = True

然后重写changelist_view

1
2
3
4
5
6
7
8
9
10
11
def changelist_view(self, request, extra_context=None):
try:
action = self.get_actions(request)[request.POST["action"]][0]
action_acts_on_all = action.acts_on_all
except (KeyError, AttributeError):
action_acts_on_all = False
if action_acts_on_all:
post = request.POST.copy()
post.setlist(ACTION_CHECKBOX_NAME, self.model.objects.all()[:1].values_list("id", flat=True))
request.POST = post
return super(MscHuaHistoryAdmin, self).changelist_view(request, extra_context)

到此,已经实现了取消自定义按钮强制选择对象的情况了,代码比较简单,主要也是参考了Stack Overflow上的回答,链接如下。

4. 参考

https://stackoverflow.com/questions/4500924/django-admin-action-without-selecting-objects
https://blog.csdn.net/qq_42761569/article/details/121495074
https://gitee.com/bode135/bddjango/blob/master/bddjango/adminclass