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

后端 未结 3 757
一整个雨季
一整个雨季 2021-02-01 02:58

I thought for whatever reason this would be easy to do, but I looked deeper and it appears there is no straightforward way to allow users to execute custom admin actions on the

3条回答
  •  没有蜡笔的小新
    2021-02-01 03:23

    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 }}
      
    {% endblock %}
    
    {% block object-tools %}
        {{ block.super }}
        
    {% csrf_token %} {% admin_actions %}
    {% endblock %}

提交回复
热议问题