Skip to content

Instantly share code, notes, and snippets.

@magopian
Last active September 10, 2021 15:51
Show Gist options
  • Save magopian/6239742 to your computer and use it in GitHub Desktop.
Save magopian/6239742 to your computer and use it in GitHub Desktop.
Small js script that automatically submits the changelist form on field changes. This is convenient when used with https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_editable, and avoids having to remember to submit the form when done (the form on the changelist page doesn't look like a form after all, …
/*
* Only useful in changelist pages when the ModelAdmin displayed has
* "list_editable" (https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_editable)
* configured.
*
* When one of the input/select/textarea value is changed, automatically submit
* the form using ajax.
*
* Only form fields relevant to the "list_editable" will trigger a form submit.
*
* This script uses the jQuery packaged with Django, and already made available
* in the admin via django.jQuery.
*
* An easy way to add this script to the admin is to override the base_site.html
* admin template (https://docs.djangoproject.com/en/dev/ref/contrib/admin/#overriding-vs-replacing-an-admin-template),
* and add the following to it:
*
* {% block footer %}{{ block.super }}
* <script type="text/javascript" src="{% static "js/admin_list_editable_autosubmit.js" %}"></script>
* {% endblock footer %}
*/
if (typeof django != 'undefined') {
(function($) {
"use strict";
$(function() {
var form = $('#changelist-form');
var inputs = $('#changelist-form input, #changelist-form select, #changelist-form textarea') // all inputs
.not('.action-select,#action-toggle,[name=action]') // but not those specific to the admin
.not('[type=hidden],[type=submit]'); // nor the hidden inputs or the submit button
$('#changelist-form [name=_save]').hide();
function form_ajax_submit() {
var data = form.serialize();
data += '&_save=1'; // add the submit button
$.post(form.attr('action'), data, display_message_from_answer);
}
function display_message_from_answer(answer) {
$('.messagelist').remove();
$('.breadcrumbs').after($(answer).find('.messagelist').fadeIn());
};
inputs.change(function() {
form_ajax_submit();
});
});
})(django.jQuery);
}
@wevoice
Copy link

wevoice commented Dec 13, 2016

Thanks so much for this. Works perfectly!

What changes would be needed to use field change to trigger the form_ajax_submit() function within the change_form pages itself? I'd really like to add this as well.

@JessiePBhalerao
Copy link

Very helpful snippet. Thank you!

@JohannesaBrahms
Copy link

Giving credit where credit is due :) Incredibly useful, thanks so much.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment