Let's imagine we have those Django models:
class Band(models.Model):
name = models.CharField(max_length=256, default="Eagles of Death Metal")
class Song(models.Model):
band = models.ForeignKey(Band)
When using the admin to manage those models, the band
field is associated to a Widget
rendered by Django as a select
html element.
Django's admin also adds a green plus icon next to the select
, clicking it opens a pop-up window where the user is presented with the Form
to add a new band. When clicking the save button in this pop-up window, the new band name is saved in the DB, and automatically assigned to the select
value.
We rely on some javascript to be run each time a select
value changes. It is currently listening to the change
event of said element, which works fine when the user clicks a value directly in the menu proposed by the select
.
Sadly, when this select
is populated through the Admin Popup functionality, it seems the change
event is not fired for the select
, as our callback is not executed, even though the element's value is actually changed.
Is there another event we can listen to to get the same behaviour than when the user clicks a value directly from the list ?
Here is a Javascript snippet with the hackery we use to trigger a change event when the Django admin's add/change popup window is dismissed.
We use this with Django 1.7, so it works for this version at least.
Monkey-patching the Django admin's JS methods to achieve this isn't a very elegant way to do the job, but it was the least intrusive option we found. If anyone knows of a better way, let us all know.
/*
* Trigger change events when Django admin's popup window is dismissed
*/
(function($) {
$(document).ready(function() {
// HACK to override `dismissRelatedLookupPopup()` and
// `dismissAddAnotherPopup()` in Django's RelatedObjectLookups.js to
// trigger change event when an ID is selected or added via popup.
function triggerChangeOnField(win, chosenId) {
var name = windowname_to_id(win.name);
var elem = document.getElementById(name);
$(elem).change();
}
window.ORIGINAL_dismissRelatedLookupPopup = window.dismissRelatedLookupPopup
window.dismissRelatedLookupPopup = function(win, chosenId) {
ORIGINAL_dismissRelatedLookupPopup(win, chosenId);
triggerChangeOnField(win, chosenId);
}
window.ORIGINAL_dismissAddAnotherPopup = window.dismissAddAnotherPopup
window.dismissAddAnotherPopup = function(win, chosenId) {
ORIGINAL_dismissAddAnotherPopup(win, chosenId);
triggerChangeOnField(win, chosenId);
}
});
})(jQuery);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With