Skip to content

Instantly share code, notes, and snippets.

@dzerrenner
Forked from cassus/admin.py
Last active December 11, 2018 12:01
Show Gist options
  • Save dzerrenner/b400511ece2e72d012b89c4407b1bb52 to your computer and use it in GitHub Desktop.
Save dzerrenner/b400511ece2e72d012b89c4407b1bb52 to your computer and use it in GitHub Desktop.
Django admin action as row button

Summary

This enables simple action buttons per entity in the admin list_view. This was adapted for Django 2.1 and is a bit more general than the original it was forked from.

Usage

Change your ModelAdmin according to the example and add user_admin.js to your static files.

class MyAdmin(admin.ModelAdmin):
class Media:
js = ('user_admin.js', )
def custom_action(self, request, queryset):
print("custom action called")
custom_cation.short_description = "Custom action"
def actions_html(self, obj):
return format_html(
'<button class="btn" type="button" onclick="inline_action({action_name}{pk})">custom_action</button>',
action_name="custom_action",
pk=obj.pk
)
actions_html.short_description = "Actions"
list_display = (..., 'actions_html', )
actions = [..., 'custom_action', ]
inline_action = function(action, pk) {
const $ = django.jQuery;
$('input[name="_selected_action"]').removeAttr('checked');
$('input[name="_selected_action"][value="{}"]'.replace('{}', pk)).attr('checked', 'checked');
$('select[name="action"]').val(action);
$('button[type="submit"][name="index"]').click();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment