Hi, I was writing a custom action with a intermediate confirmation page and noticed that without the hidden input _selected_action it didn’t work properly.
Here’s the code I’ve written:
the action
def bulk_manage_user_functions(modeladmin, request, queryset):
action = request.POST["action"]
action_descripition_mapper = {
"bulk_activate_users": "activate",
"bulk_deactivate_users": "deactivate",
"bulk_suspend_users": "suspend",
}
action_form_mapper = {
"bulk_suspend_users": SuspendUserForm,
}
action_description = action_descripition_mapper[action]
action_context = {
"site": modeladmin.admin_site,
"action": action,
"title": f"{action_description.capitalize()} Users",
"action_description": action_description,
"queryset": queryset,
"confirmation": request.POST.get("confirmation", ""),
}
if action_form_mapper.get(action):
form = action_form_mapper[action]
action_context["form"] = form
if request.POST.get("confirmation") is None:
return TemplateResponse(request, "admin/base_bulk_users_management.html", action_context)
if action == "bulk_activate_users":
queryset.update(is_active=True)
messages.success(request, f"{queryset.count()} users activated successfully")
elif action == "bulk_deactivate_users":
queryset.update(is_active=False)
messages.success(request, f"{queryset.count()} users deactivated successfully")
elif action == "bulk_suspend_users":
suspend_users(request, request.POST, queryset)
the template (the input part, the rest is just a base template with the form)
{% for obj in queryset %}
<input type="hidden" name="_selected_action" value="{{ obj.pk }}" />
{% endfor %}
I don’t get it, since we’re going to create various inputs with the same name, will the action only applies to the last one in the for loop? Shouldn’t the value be the whole queryset?