Setting Default Values in Django Admin (with Greasemonkey)
The Django Admin interface is the best thing since sliced bread. Its flexible enough to handle 80% of everyday needs and built so that handling the other 20% isn't too bad. Generally speaking, its pretty good for entering data.
Little things like setting default fields can dramatically speed up the data entry process. When you repeat a process hundreds of times, a 30 second improvement can be significant.
Which is why it bugged me that I couldn't set default values for my admin.TabularInline field:
The result was an extra minute for every host I was entering in to Hosting Choice.
After speaking with some people in #django on irc.freenote.net I realized Greasemonkey would be the best way to tackle this problem. Apparently, sub-classing the admin.TabularInline class is more trouble than it's worth.
The Greasemonkey solution is a little dirty, but it definitely gets the job done. It could have make the script shorter, but I opted to include jQuery--because I find Javascript without jQuery these days maddening.
The end result is this:
Here's the script in all its mighty. To set your own default values, adjust the defaults dictionary at the top. The keys are jQuery selectors and the values are whatever your default value is.
// ==UserScript== // @name Django Default Admin // @namespace /django_admin // @description Script fot setting default values in the Django Admin // @include http://hosting-choice.com/admin/catalog/host/add/ // ==/UserScript==// Syntax is {#id, 'default value'} defaults = { '#id_feature_set-0-type': 'Price', '#id_feature_set-0-value': 6.95, '#id_feature_set-1-type': 'Bandwidth', '#id_feature_set-1-value': 0, '#id_feature_set-2-type': 'Space', '#id_feature_set-2-value': 0}
// Attach jQuery var GM_JQ = document.createElement('script'); GM_JQ.src = 'http://jquery.com/src/jquery-latest.js'; GM_JQ.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(GM_JQ);
// Check if jQuery's loaded function GM_wait() { if (typeof unsafeWindow.jQuery == 'undefined') { window.setTimeout(GM_wait,100); } else { $ = unsafeWindow.jQuery; letsJQuery(); } }
GM_wait();
function letsJQuery() { for (id in defaults) { $(id).val(defaults[id]); } }
This entry was published on Feb. 6, 2009 in Web Development
Comments