Archive for the ‘Uncategorized’ Category

Named Scopes for Django

Monday, June 22nd, 2009

There are really only a handful of features I miss about Ruby on Rails, having switched over to using only Django about a year ago. One of the biggest among these has been named scopes.

What a named scope does in Rails, in Django terms, is allow you to name a given query and use it as a base, or “scope,” for further queries. In other words, your narrowing down the results upon which additional queries that you run will be executed.

It’s pretty much the same idea behind modifying initial Manager QuerySets as outlined in the Django documentation, with one major difference: Scopes can be chained. Chaining is the feature I had long coveted, and I had been banging my head around for a solution for the last few months.

The other day while I was poking around the internals a bit though, a decent idea came to me. I realized it would be quite simple for me to extend the default Manager class with an attribute where I could store QuerySet methods I wanted to execute as part of a scope, and then overwrite get_query_set() with a hook that ran these methods before executing the rest of the query.

This turned out to be a nice strategy, and with the addition of some decorators the interface itself turned out to be extraordinarily simple.

(more…)

Organizing Unit Tests in Django

Wednesday, February 25th, 2009

I just started a small side project last week, and I finally decided to take the opportunity to really make TDD (test-driven development) happen for me using Django. Though I’ve dabbled with testing in Django and done quite a bit more with testing in Ruby, I never managed to embrace TDD fully. It’s about time, I figure.

Well, I hit some snags as I got underway. Partly this had to do with me being something of a novice when it comes to testing, and partly it has to do with the state of testing in Django at present.

My mini-gripe with testing in Django is that it’s just kind of loosey-goosey. You can use doctest, or you can use unittest. You can put your tests in your functions, or in your models, or in tests.py, or in a tests/ subfolder.

For me at least, I want my framework to be a bit more opinionated. I want a bunch of guys who are all smarter than me to have sat around and thought about (or better yet, generalized from a working production code) things like the best way to configure testing for a Python web framework, and then to tell me, in no uncertain terms, the exact way to do it.

I’m obviously exaggerating a bit, and I don’t really mean at all to rant about a phenomally awesome, not to mention open source, framework like Django. What all of the above amounts to is that I had to ponder deeply on the problem space myself and come up with a way of structuring my test code that would work for me.

So that’s what I did, and here is the organizational structure I intend to use as I proceed.

(more…)

Prepending an Indefinite Article (a or an) in Front of a Word or Phrase

Monday, January 26th, 2009

Today, I had to whip up a Django template tag to add “a” or “an” in front of a phrase.

It started off pretty easy — just use “an” when the first letter of the phrase is a vowel and otherwise use “a.” And then I remembered about abbreviations (“an HR department”), silent H words (“an honorable man”), and exceptions among a few O and U words (“a one-time offer” or “a union representative”), and suddenly it wasn’t so easy.

Fortunately I managed to find an excellent database of English words that includes pronunciations, and in no time at all I was able to generate a list of exceptions.

Here’s the final result, implemented as a custom django template tag (in my use case, I needed to able to wrap the original phrase in an HTML tag, so I couldn’t use a filter tag). This could also easily be a standalone Python function as well (literally by removing the @register.simple_tag decorator).

(more…)

JSON Parsing and Stringifying in jQuery (as a plugin)

Thursday, January 15th, 2009

jQuery has many kick-ass javascript utilities. Among these is a method (jQuery.getJSON()) that parses JSON that you grab from a remote source and gives it back to you as a JSON object. Excellent!

Surprisingly though, jQuery (as of 1.3, to my knowledge anyway) does not make any functions available to allow you to securely parse a simple text string into JSON. Not sure why this is so, especially since they must do it behind the scenes for the getJSON() method, but so be it.

I needed this functionality, though, so I could pass some data from one of my templates to a jQuery function I’m working on.

Fortunately, even though jQuery doesn’t have built-in functionality for this, it was relatively trivial to wrap the open source JSON parsing and stringifying library published by JSON.org in an easy-to-use jQuery plugin.

So that’s what I did. I changed nothing of the JSON parsing library implementation published by JSON.org; I just wrapped two jQuery methods around it, as follows:

;(function($) {
    if (!this.JSON) {
        var JSON = {};
    }
    /* ... implementation of parse() and stringify() here ... */
    $.toJSON = function(text, reviver) {
        if (typeof reviver == "undefined") {
            reviver = null;
        }
        return JSON.parse(text, reviver);
    };
    $.jSONToString = function(value, replacer, space) {
        if (typeof replacer == "undefined") {
            replacer = null;
        }
        if (typeof space == "undefined") {
            space = null;
        }
        return JSON.stringify(value, replacer, space);
    };

})(jQuery);

Pretty convenient. Now I can securely parse and decode JSON to my heart’s content.

Here’s the source code of the full jQuery JSON plugin, if you’re interested. Note that I have not extensively tested the plugin, but since I did not actually touch any part of the JSON parsing library it’s based on (save for creating a local scope for the JSON variable), I wouldn’t foresee any issues.

Here’s a bit more information about the library the plugin is based on.

An HTML Primer for Writers and Editors

Tuesday, January 6th, 2009

A year ago, I wrote up a brief primer on HTML for some colleagues that was intended for writers and editors. By this I mean I tried to keep technical jargon to a minimum and focused on appealing to writers’ and editors’ love of semantics and grammar.

I was just forwarding it to someone who didn’t know any HTML, and I figured it makes sense to post it here for the benefit of anyone else who stumbles upon it.

Why You Should Care About HTML

For writers and editors, HTML probably seems at best like a minor nuisance. The fact that it was written by (and to some extent conceived of for) programmers is probably a big reason why.

In fact, HTML is pretty easy to learn conceptually. And these days, HTML has mostly been stripped of what once made it a “programming” or design language. Properly used, HTML has now become a way for content authors to define the meaning of various aspects of a web document. In fact, content authors and editors are really the only people who can properly mark up a document and ensure it’s being done correctly.

Here are just a few of the reasons why you should care (passionately) about HTML:

(more…)

Capturing AutoFill as a Change Event

Friday, January 2nd, 2009

I was working on a form design recently in which I wanted the corresponding labels to disappear whenever text was entered into an input field.

This was easy enough to accomplish via jQuery, but I quickly hit a snag. I had assigned an event listener to the “change” event, but it turns out that the change event only gets fired when a user actively focuses on a field, inputs text, and then blurs. If a script — such as Google AutoFill — updates a value in a field on its own, the change event is unaware of it.

I poked around on Google a bit, and as far as I can tell, there doesn’t really seem to be an easy answer for this. So to make it work, I decided to write a quick jQuery plugin to handle the job.

I realized fortunately that rather than reinvent the wheel, all I need to do was find a way to listen for changes to input fields and then fire the change event manually if they were altered outside of the usual focus/blur routine (i.e. by a script).

Here’s the plugin code I came up with:

(function($) {
    $.fn.listenForChange = function(options) {
        settings = $.extend({
            interval: 200 // in microseconds
        }, options);

        var jquery_object = this;
        var current_focus = null;

        jquery_object.filter(":input").add(":input", jquery_object).focus( function() {
            current_focus = this;
        }).blur( function() {
            current_focus = null;
        });

        setInterval(function() {
            // allow
            jquery_object.filter(":input").add(":input", jquery_object).each(function() {
                // set data cache on element to input value if not yet set
                if ($(this).data('change_listener') == undefined) {
                    $(this).data('change_listener', $(this).val());
                    return;
                }
                // return if the value matches the cache
                if ($(this).data('change_listener') == $(this).val()) {
                    return;
                }
                // ignore if element is in focus (since change event will fire on blur)
                if (this == current_focus) {
                    return;
                }
                // if we make it here, manually fire the change event and set the new value
                $(this).trigger('change');
                $(this).data('change_listener', $(this).val());
            });
        }, settings.interval);
        return this;
    };
})(jQuery);

The plugin makes use of the trigger() and data() functions. In a nutshell, we loop over the input element or set of children input elements, storing their initial value in the data cache provided by the data() function. We then check to see if the stored value matches the value of the input during the current iteration. If so, we do nothing, if not, we manually fire the change event via trigger().

There’s also a bit of logic in there to ignore the element that has focus. We don’t need to worry about this element, since if the value is changed while the user has focus, the change event will be fired as normal when the element is blurred.

That’s all there is to it. To use the plugin, you simply call listenForChange() on the form or input you want to listen on, e.g.:

$("form").listenForChange();

You can then assign whatever functions you want triggered to the change event as normal, and they’ll be fired regardless of whether the user types them or they are updated via a script.

I’ve tested this on Firefox with Google AutoFill and Safari’s built-in AutoFill, and it seems to work on both. I haven’t tested it on fields injected after page load, but presumably it would work for these as well.

The Glass Hammer Wins Blog of the Year Award!

Monday, November 17th, 2008

My congratulations go out to Nicki Gilmour and the gang of outstanding editors and contributors over at The Glass Hammer, who won a prestigious Stevie Award for Best Blog of the Year. The Glass Hammer was designed and developed by Furry Brains, and is based on Wordpress.

I’m not sure Furry Brains can take much credit for having a role in their winning this award, since it’s really the outstanding writing day in and day out that makes The Glass Hammer such a great publication. If anything, the design and implementation of the website step out of the way for the content itself to shine through.

But I’m pleased and proud if my contribution at least in some small way helped them get there. Way to go, TGH!

Address on the Spot: Using Google’s Reverse Geocoding API

Saturday, November 1st, 2008

Google just launched a new feature as part of its geolocation services: a Reverse Geocoding feature as part of the Google Maps API.

The API is really simple to use. It took me only a few hours to put together a quick little utility called Address on the Spot, which allows you to double click anywhere on a map to find an address for a location.

So here’s a quick how to for using the Reverse Geocoding API.

First, create a GLatLng object with a set of geocoordinates:

point = new GLatLng(45.523875, -122.670399);

Next, create a GClientGeocoder object and pass the point object to it, along with a callback function. The callback function display_address() will be executed when the geocoder returns a response.

geocoder = new GClientGeocoder();
geocoder.getLocations(point, display_address);

Here’s what display_address() might look like:

function display_address(response) {
    var address;
    if (!response || response.Status.code != 200) {
        address = "No location data found."
    } else {
        address = response.Placemark[0].address;
    }
    alert(address);
}

Couldn’t be easier. It’s definitely a handy addition to the Google Maps API, and this utility was pretty fun and easy to build.

Using “in” in QuerySets in Django

Thursday, October 23rd, 2008

So the purpose of this post is just to look at a neat way of solving a problem in Django, and explain its mechanics and how it was put together.

In today’s example, the goal was pretty straightforward. We have a model class, Topic, that has a one-to-many relationship to a ThreadedComment model class. Each ThreadedComment for each Topic, has a User associated with it; furthermore the Topic itself as a User associated with it (the creator of the topic).

(more…)

Figuring Out the Implementation of a Math Function Using Grapher on Mac OS X

Monday, October 13th, 2008

In a side project I’m working on right now in Django/Python, I need to do some work with latitudes and longitudes on a map. What follows is a description of how I tackled on of the specific challenges I faced.

In a nutshell, I’m going to be working with some data sets that are grouped into grid squares on a map. The grid squares are based on the integer values of latitudes and longitudes, which I have arbitrarily chosen to identify by the coordinates at their southwest corner.

So let’s put this in a picture to make it a bit easier to visualize. Basically, just try to visualize a flat map of the Earth. Longitude runs E/W along the X axis, with 0 degrees being the central horizontal point and 180/-180 degrees being the edges (which are actually the same thing, since the Earth wraps around in a sphere), while latitude runs N/S (along the Y axis), with 90 being the north pole and -90 being the south.

Note the following map isn’t really to “scale,” in the sense that the coordinate system I am using doesn’t perfectly match up in the real world with the map behind it. I’m just using the map to help visualize the grid:

(more…)