Skip to content

Instantly share code, notes, and snippets.

@wolph
Last active December 2, 2016 00:02
Show Gist options
  • Save wolph/36f5f239fd440a163e5e46667fda9f2f to your computer and use it in GitHub Desktop.
Save wolph/36f5f239fd440a163e5e46667fda9f2f to your computer and use it in GitHub Desktop.
Firefox console script to extract `fields` and `fieldset` definitions from django admin form/edit pages
console.clear();
function getFields(fields, parent){
var rows = [" fields = ("];
$(fields, parent).each(function(){
var regex = /field-([^ ]+)/g;
var columns = [];
while(match = regex.exec(this.className)){
columns.push(match[1]);
}
if(columns.length == 1){
rows.push(" '" + columns[0] + "',");
}else{
rows.push(" ('" + columns.join("', '") + "'),");
}
});
rows.push(" )");
return rows.join('\n');
}
var fields = getFields('fieldset.module:first>div.form-row');
console.info(fields);
/* Copy to the clipboard if it's available */
if(typeof(copy) !== 'undefined')copy(fields);
$('div.inline-group').each(function(){
console.info(this.id.replace(/_set.*/, ''));
console.info(getFields('tr.form-row:first td[class^=field-]', this));
});
console.clear();
Array.prototype.remove = function() {
var what, a = arguments, L = a.length, ax;
while (L && this.length) {
what = a[--L];
while ((ax = this.indexOf(what)) !== -1) {
this.splice(ax, 1);
}
}
return this;
};
var fieldsets = [];
function getFieldset(fields, parent){
var fieldset = [];
$(fields, parent).each(function(){
var regex = /field-([^ ]+)/g;
var columns = [];
while(match = regex.exec(this.className)){
columns.push(match[1]);
}
fieldset.push(columns);
});
return fieldset;
}
function repeatChar(n, c){
return new Array(n + 1).join(c);
}
function pad(str, n){
return repeatChar(n, ' ') + str;
}
var out = [''];
out.push(pad('fieldsets = (', 4));
var q = "'";
$('form>div>fieldset.module').each(function(){
var name = $('h2', this).text();
var fieldset = getFieldset('div.form-row', this);
if(name){
name = q + name + q;
}else{
name = 'None';
}
out.push(pad('(' + name + ', {', 8));
out.push(pad("'fields': (", 12));
$.each(fieldset, function(i, fields){
if(fields.length == 1){
out.push(pad(q + fields[0] + q + ',', 16));
}else{
out.push(pad("('" + fields.join("', '") + "'),", 16));
}
});
out.push(pad('),', 12));
var classes = this.className.split(' ');
classes.remove('module');
classes.remove('aligned');
classes.remove('');
if(classes.length == 1){
out.push(pad("'classes': ('" + classes + "',),", 12));
}else if(classes.length > 1){
out.push(pad("'classes': ('" + classes.join("', '") + "'),", 12));
}
console.info(classes);
out.push(pad('}),', 8));
});
out.push(' )')
/* Copy to the clipboard if it's available */
if(typeof(copy) !== 'undefined')copy(out.join('\n'));
out.join('\n')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment