Django custom fields: descriptor class gotcha

Let’s say you are making a custom field type that uses different attname and name properties, like ForeignKey fields do.

Probably this is so that you can store the raw value in the db under field.attname, while transparently accessing a converted value via

Probably to make that mechanism work you are needing a descriptor class, much like a ForeignKey field has a ReverseSingleRelatedObjectDescriptor which handles the get/set functionality for the field – allowing you to get or set model instances, while a plain id is saved in the db under field.attname.

Since there’s no specific docs on how to do this you probably started by copying Django’s example, like the ForeignKey mechanism above. Continue reading “Django custom fields: descriptor class gotcha”

quickie: jQuery array comparison helper

I was looking for an answer to this question today an ended up answering it myself.

    arrayCompare: function (arrayA, arrayB) {
        if (arrayA.length != arrayB.length) { return false; }
        // sort modifies original array
        // (which are passed by reference to our method!)
        // so clone the arrays before sorting
        var a = jQuery.extend(true, [], arrayA);
        var b = jQuery.extend(true, [], arrayB);
        for (var i = 0, l = a.length; i < l; i++) {
            if (a[i] !== b[i]) { 
                return false;
        return true;

var a = [1, 2, 3];
var b = [2, 3, 4];
var c = [3, 4, 2];

jQuery.arrayCompare(a, b);
// false

jQuery.arrayCompare(b, c);
// true

// c is still unsorted [3, 4, 2]

Python-style template strings for AS3

public class StringTemplate
* Mimics the python template string format, eg:
* "blah blah %(varname)s blah blah"
* then you pass in a 'dict' of varnames which get
* substituted into the string when run.
public static function parse(str:String, vars:Object):String
var re:RegExp = /\%\((\w+)\)s/g;
var match:Object;
while((match=re.exec(str)) !== null) {
if (vars.hasOwnProperty(match[1])) {
str = str.replace(match[0], vars[match[1]]);
return str;

Currently only handles the ‘dict of vars’ style substitution and probably doesn’t handle escaping and other edge-cases properly. Fine for a bit of quick and dirty string action though.

Posted in AS3

JS+Django: streaming multi-part ajax responses (MXHR)

Ajax is great eh? What did it stand for again…? Asynchronuous Javascript And XML?

Anyone actually sending back XML in their Ajax app these days?

I find, if I have the choice, I’m using JSON for sending the data back. Then, for those times where you don’t want to duplicate all of the templating logic from the server in your Javascript code just to ‘Ajax’ a form or something, I find I will often render a bit of HTML and send that back, even if it feels a bit dirty. It’s easy and there’s a certain DRYness that’s undeniable.

So it’s only a matter of time before you start thinking, as I did, “Sure, I could make half a dozen separate XHR requests, but what I really need to do here is send back a package of identifiable HTML and JSON chunks.”

Some kind of multi-part response basically. Hang on, I’ve heard of that before… something to do with email, or file uploads?

Continue reading “JS+Django: streaming multi-part ajax responses (MXHR)”

Django: optiongroups for your ModelChoice Field

With a normal Django ChoiceField you can specify choices either as a simple tuple of tuples (value, label pairs) or with an extra level structure to organise the choices into named groups. The Django Select widget will then happily render the choices into html optiongroups.

With a ModelChoiceField you don’t specify the choices directly, you give a queryset of results from the db, which just has a flat structure.

I’ve made a ‘GroupedModelChoiceField’ that allows to output optiongroups based on a field from the model in your queryset. Code is here on djangosnippets… simple as that!

More django-mptt goodness: FilteredSelectMultiple m2m widget

If you are using django-mptt to manage content (eg heirarchical categories) then it needs a bit of help to make a nice admin interface. For many-to-many fields, Django provides the quite nice FilteredSelectMultiple widget (a two-pane selection list with search box) but it only renders ‘flat’ lists… if you have a big category tree it’s going to be confusing to know what belongs to what. Also, list items are sorted alphabetically by the js, which won’t be what you want.

In this post I’ll be extending FilteredSelectMultiple to show the tree structure in the list:

Continue reading “More django-mptt goodness: FilteredSelectMultiple m2m widget”