Is there a way to get custom Django admin actions to appear on the “change” view in addition to the “change list” view?

Here is update and improvement of this answer. It works with django 1.6 and redirects to where you came from.

class ActionInChangeFormMixin(object):
    def response_action(self, request, queryset):
        """
        Prefer http referer for redirect
        """
        response = super(ActionInChangeFormMixin, self).response_action(request,
                queryset)
        if isinstance(response, HttpResponseRedirect):
            response['Location'] = request.META.get('HTTP_REFERER', response.url)
        return response  

    def change_view(self, request, object_id, extra_context=None):
        actions = self.get_actions(request)
        if actions:
            action_form = self.action_form(auto_id=None)
            action_form.fields['action'].choices = self.get_action_choices(request)
        else: 
            action_form = None
        extra_context=extra_context or {}
        extra_context['action_form'] = action_form
        return super(ActionInChangeFormMixin, self).change_view(request, object_id, extra_context=extra_context)

class MyModelAdmin(ActionInChangeFormMixin, ModelAdmin):
    ......

Template:

{% extends "admin/change_form.html" %}
{% load i18n admin_static admin_list admin_urls %}

{% block extrastyle %}
  {{ block.super }}
  <link rel="stylesheet" type="text/css" href="https://stackoverflow.com/questions/2805701/{% static"admin/css/changelists.css" %}" />
{% endblock %}

{% block object-tools %}
    {{ block.super }}
    <div id="changelist">
    <form action="{% url opts|admin_urlname:'changelist' %}" method="POST">{% csrf_token %}
        {% admin_actions %}
        <input type="hidden" name="_selected_action" value="{{ object_id }}">
    </form>
    </div>
{% endblock %}

Leave a Comment