有没有办法覆盖这个
行为并让动作运行
还是?
我要说不,没有简单的方法。
如果您对错误消息进行 grep,您会看到代码在 django.contrib.admin.options.py 中,并且问题代码在 changelist_view 的深处。
action_failed = False
selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME)
# Actions with no confirmation
if (actions and request.method == 'POST' and
'index' in request.POST and '_save' not in request.POST):
if selected:
response = self.response_action(request, queryset=cl.get_query_set())
if response:
return response
else:
action_failed = True
else:
msg = _("Items must be selected in order to perform "
"actions on them. No items have been changed.")
self.message_user(request, msg)
action_failed = True
它也用于response_action 函数,因此您不能只覆盖 changelist_template 并使用它——定义您自己的动作有效性检查器和运行器将是最简单的。
如果您真的想使用该下拉列表,这里有一个没有保证的想法。
如何为您的无选择管理操作定义一个新属性:myaction.selectionless = True
将response_action 功能复制到覆盖的changelist_view 中,该功能仅适用于指定特定标志的操作,然后返回“真实”changelist_view
# There can be multiple action forms on the page (at the top
# and bottom of the change list, for example). Get the action
# whose button was pushed.
try:
action_index = int(request.POST.get('index', 0))
except ValueError:
action_index = 0
# Construct the action form.
data = request.POST.copy()
data.pop(helpers.ACTION_CHECKBOX_NAME, None)
data.pop("index", None)
# Use the action whose button was pushed
try:
data.update({'action': data.getlist('action')[action_index]})
except IndexError:
# If we didn't get an action from the chosen form that's invalid
# POST data, so by deleting action it'll fail the validation check
# below. So no need to do anything here
pass
action_form = self.action_form(data, auto_id=None)
action_form.fields['action'].choices = self.get_action_choices(request)
# If the form's valid we can handle the action.
if action_form.is_valid():
action = action_form.cleaned_data['action']
select_across = action_form.cleaned_data['select_across']
func, name, description = self.get_actions(request)[action]
if func.selectionless:
func(self, request, {})
调用“真实”操作时仍然会出现错误。如果调用了覆盖的操作,您可能会修改 request.POST 以删除该操作。
其他方式涉及入侵太多东西。我认为至少。