You may want to execute some JavaScript when an inline form is added or removed in the admin change form. The formset:added and formset:removed jQuery events allow this. The event handler is passed three arguments:
The event is fired using the django.jQuery namespace.
In your custom change_form.html template, extend the admin_change_form_document_ready block and add the event listener code:
{% extends 'admin/change_form.html' %}
{% block admin_change_form_document_ready %}
{{ block.super }}
<script type="text/javascript">
(function($) {
$(document).on('formset:added', function(event, $row, formsetName) {
if (formsetName == 'author_set') {
// Do something
}
});
$(document).on('formset:removed', function(event, $row, formsetName) {
// Row removed
});
})(django.jQuery);
</script>
{% endblock %}
Two points to keep in mind:
Sometimes you’ll need to work with jQuery plugins that are not registered in the django.jQuery namespace. To do that, simply change how the code listens for events. Instead of wrapping the listener in the django.jQuery namespace, just listen to the event triggered from there. For example:
{% extends 'admin/change_form.html' %}
{% block admin_change_form_document_ready %}
{{ block.super }}
<script type="text/javascript">
django.jQuery(document).on('formset:added', function(event, $row, formsetName) {
// Row added
});
django.jQuery(document).on('formset:removed', function(event, $row, formsetName) {
// Row removed
});
</script>
{% endblock %}
Mar 31, 2016