<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Flapping Head</title>
	<atom:link href="http://scottbarnham.com/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://scottbarnham.com/blog</link>
	<description>Code and comments on web development, Django, Python and things (un)related.</description>
	<lastBuildDate>Thu, 08 Jul 2010 09:49:01 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Porting MooTools to jQuery</title>
		<link>http://scottbarnham.com/blog/2010/07/08/porting-mootools-to-jquery/</link>
		<comments>http://scottbarnham.com/blog/2010/07/08/porting-mootools-to-jquery/#comments</comments>
		<pubDate>Thu, 08 Jul 2010 09:49:01 +0000</pubDate>
		<dc:creator>Scott</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[mootools]]></category>

		<guid isPermaLink="false">http://scottbarnham.com/blog/?p=58</guid>
		<description><![CDATA[Last night I ported some JavaScript code that used MooTools to use jQuery instead.  In many ways I prefer MooTools to jQuery, but jQuery is easier to integrate in code that uses other libraries (e.g. Prototype).
Here&#8217;s a few quick hints for things you need to change if you&#8217;re doing the same.
$(&#8216;element_id&#8217;)
You need a leading [...]]]></description>
			<content:encoded><![CDATA[<p>Last night I ported some JavaScript code that used MooTools to use jQuery instead.  In many ways I prefer MooTools to jQuery, but jQuery is easier to integrate in code that uses other libraries (e.g. Prototype).</p>
<p>Here&#8217;s a few quick hints for things you need to change if you&#8217;re doing the same.</p>
<h3>$(&#8216;element_id&#8217;)</h3>
<p>You need a leading hash: <code>$('#element_id')</code></p>
<p>No need for two dollars to use selectors: <code>$('#element_id form input.special')</code> works.</p>
<p>There&#8217;s a difference of approach to what happens when you use <code>$(...)</code>: MooTools adds stuff to the DOM element.  jQuery gives you a new object which wraps the element.  This means you can&#8217;t just call DOM stuff on the object jQuery gives you.  e.g.</p>
<p>MooTools:<br />
<code>$$('a.special_link').href</code> &#8211; access the normal DOM properties</p>
<p>jQuery<br />
<code>$('a.special_link').attr('href')</code> &#8211; ask the jQuery object to access the underlying DOM element</p>
<p>A jQuery object can represent a list of elements, not just a single one.  You can access the underlying element using index zero: <code>$('a.special_link')[0].href</code></p>
<h3>Class</h3>
<p>jQuery doesn&#8217;t do classes.  There&#8217;s code and plugins around, or you can use a standard JavaScript approach like:</p>
<pre>var MyClass = function(blah) {
    // this is your constructor
    this.blah = blah;
};
MyClass.prototype.doStuff = function(name) {
    // this is a member function
    return this.blah + name;
}

// instantiate and call like normal
var thing = new MyClass('hello');
thing.doStuff('monty');
</pre>
<h3>bind(this)</h3>
<p>Oh this one hurts.  When you have a function, perhaps a callback, that you want to reference your class instance as &#8220;<code>this</code>&#8220;, in MooTools you use something like:</p>
<pre>new Request.JSON({url: '...', onSuccess: function(data){
    this.doStuff(data.name);
}<strong>.bind(this)</strong>);</pre>
<p>The equivalent is to use JavaScripts <code>apply</code> method which lets you pass an object to use for &#8220;<code>this</code>&#8220;.  You might also want &#8220;<code>arguments</code>&#8221; which is an array of all arguments passed to the function.  e.g.</p>
<pre>var self = this;
$.getJSON('...', <strong>function(){return</strong> function(data){
    this.doStuff(data.name);
}<strong>.apply(self, arguments)}</strong>);</pre>
<h3>addEvent</h3>
<p>This is what jQuery calls <code>bind</code>.  e.g.</p>
<pre>$('#element_id a').bind('click', function(e){..});</pre>
<h3>each</h3>
<p>Instead of MooTools&#8217; <code>$$('a.special').each(function(elem){...})</code></p>
<p>Try <code>$.each($('a.special'), function(index, elem){...})</code>.  Note the first param to your function is index, not the element.</p>
<h3>Request.JSON</h3>
<p>As above, try <code>$.getJSON(url, func)</code>.  You can also use <code>$.post</code> if it&#8217;s a POST request (seems to decode the JSON response automatically).</p>
<h3>get and set</h3>
<p>Instead of <code>elem.get('href')</code> try <code>elem.attr('href')</code>.  Instead of <code>elem.set('text', 'blah')</code> there&#8217;s <code>elem.text('blah')</code>.</p>
<p>That&#8217;s my braindump for now.</p>
]]></content:encoded>
			<wfw:commentRss>http://scottbarnham.com/blog/2010/07/08/porting-mootools-to-jquery/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Staplefish joins Red Robot Studios</title>
		<link>http://scottbarnham.com/blog/2010/03/18/staplefish-joins-red-robot-studios/</link>
		<comments>http://scottbarnham.com/blog/2010/03/18/staplefish-joins-red-robot-studios/#comments</comments>
		<pubDate>Thu, 18 Mar 2010 11:58:58 +0000</pubDate>
		<dc:creator>Scott</dc:creator>
				<category><![CDATA[Business]]></category>

		<guid isPermaLink="false">http://scottbarnham.com/blog/?p=53</guid>
		<description><![CDATA[I&#8217;ve been working as a freelancer under the Staplefish business name for over four years now.  Since mid-2008, I&#8217;ve also be working with Andrew at our Red Robot Studios business.
I&#8217;m moving all my Staplefish work under the Red Robot Studios brand.  The aim is to simplify some business things (accounting, tax, invoicing, etc) [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been working as a freelancer under the Staplefish business name for over four years now.  Since mid-2008, I&#8217;ve also be working with Andrew at our <a href="http://www.redrobotstudios.com/">Red Robot Studios</a> business.</p>
<p>I&#8217;m moving all my Staplefish work under the Red Robot Studios brand.  The aim is to simplify some business things (accounting, tax, invoicing, etc) and offer better service by teaming up with Andrew (e.g. one of us can cover while the other goes on holiday).  It also marks our decision to focus on Red Robot Studios and offer great <a href="http://www.redrobotstudios.com/django-development/">Django development</a> and <a href="http://www.redrobotstudios.com/mobile-development/">mobile development</a> services.</p>
<p>To all Staplefish clients: Please be assured Scott is still working for you, just under a different business name and your websites will not be affected.  Feel free to contact me with any questions or concerns.</p>
]]></content:encoded>
			<wfw:commentRss>http://scottbarnham.com/blog/2010/03/18/staplefish-joins-red-robot-studios/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Emulating Django blocks with Smarty capture</title>
		<link>http://scottbarnham.com/blog/2010/01/02/emulating-django-blocks-with-smarty-capture/</link>
		<comments>http://scottbarnham.com/blog/2010/01/02/emulating-django-blocks-with-smarty-capture/#comments</comments>
		<pubDate>Fri, 01 Jan 2010 23:34:15 +0000</pubDate>
		<dc:creator>Scott</dc:creator>
				<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://scottbarnham.com/blog/?p=41</guid>
		<description><![CDATA[Django blocks considered addictive
I do Django development for Red Robot Studios and one of the many great things about the Django web framework is the template system.
Using blocks and inheritance, repetitive html is kept to a minimum.  For example you can do:
base.html
...
&#60;title&#62;{% block title %}Default Title{% endblock %}&#60;/title&#62;
...
&#60;div id="content"&#62;
{% block content %}{% endblock %}
&#60;/div&#62;
...
home.html
{% [...]]]></description>
			<content:encoded><![CDATA[<h2>Django blocks considered addictive</h2>
<p>I do <a href="http://www.redrobotstudios.com/">Django development</a> for Red Robot Studios and one of the many great things about the <a href="http://www.djangoproject.com/">Django web framework</a> is the template system.</p>
<p>Using <a href="http://docs.djangoproject.com/en/dev/topics/templates/#id1">blocks and inheritance</a>, repetitive html is kept to a minimum.  For example you can do:</p>
<p>base.html</p>
<pre>...
&lt;title&gt;{% block title %}Default Title{% endblock %}&lt;/title&gt;
...
&lt;div id="content"&gt;
{% block content %}{% endblock %}
&lt;/div&gt;
...</pre>
<p>home.html</p>
<pre>{% extends 'base.html' %}{% block title %}Home Page Title{% endblock %}
{% block content %}
Home page content here
{% endblock %}</pre>
<p>The content of the blocks in home.html are plugged in to the block placeholders in base.html.</p>
<h2>Smarty doesn&#8217;t have blocks like Django</h2>
<p><a href="http://www.smarty.net/">Smarty</a> is a template system for php.  I was using it recently for a client and wished I could use Django-style blocks.  Smarty doesn&#8217;t have blocks and inheritance, but does have capture and include.  Here&#8217;s how I was able to achieve a similar result.</p>
<h2>Using Smarty capture to emulate blocks</h2>
<p>Using Smarty&#8217;s <a href="http://www.smarty.net/manual/en/language.builtin.functions.php#language.function.capture">capture</a> and <a href="http://www.smarty.net/manual/en/language.function.include.php">include</a> functions, here&#8217;s how the templates look:</p>
<p>header.tpl</p>
<pre>...
&lt;title&gt;{if $smarty.capture.title}{$smarty.capture.title}{else}Default Title{/if}&lt;/title&gt;
...
&lt;div id="content"&gt;
{$smarty.capture.content}
&lt;/div&gt;
...</pre>
<p>home.tpl</p>
<pre>{capture name='title'}Home Page Title{/capture}
{capture name='content'}
Home page content here
{/capture}

{include file='header.tpl'}
</pre>
<p>Simple, no?  Remember to do these captures before including the file.</p>
<p>It&#8217;s not as powerful as Django template inheritance, but it&#8217;s a reasonable attempt to use Django-style blocks in Smarty templates.</p>
]]></content:encoded>
			<wfw:commentRss>http://scottbarnham.com/blog/2010/01/02/emulating-django-blocks-with-smarty-capture/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Migrating Postgresql Databases the Easy Way</title>
		<link>http://scottbarnham.com/blog/2009/06/23/migrating-postgresql-databases-the-easy-way/</link>
		<comments>http://scottbarnham.com/blog/2009/06/23/migrating-postgresql-databases-the-easy-way/#comments</comments>
		<pubDate>Tue, 23 Jun 2009 10:45:52 +0000</pubDate>
		<dc:creator>Scott</dc:creator>
				<category><![CDATA[Postgresql]]></category>

		<guid isPermaLink="false">http://scottbarnham.com/blog/2009/06/23/migrating-postgresql-databases-the-easy-way/</guid>
		<description><![CDATA[When you upgrade Postgresl to a new major version (e.g. 8.1 to 8.3), all databases need to be dumped from the old version and loaded in to the new version.  It&#8217;s not difficult, but on Debian there&#8217;s a really easy way.
Debian has pg_createcluster, pg_dropcluster and pg_upgradecluster (plus a few others).  The one I&#8217;m [...]]]></description>
			<content:encoded><![CDATA[<p>When you upgrade Postgresl to a new major version (e.g. 8.1 to 8.3), all databases need to be dumped from the old version and loaded in to the new version.  It&#8217;s not difficult, but on Debian there&#8217;s a really easy way.</p>
<p>Debian has <code>pg_createcluster</code>, <code>pg_dropcluster</code> and <code>pg_upgradecluster</code> (plus a few others).  The one I&#8217;m referring to here is <code>pg_upgradecluster</code>.</p>
<p>It takes the version and cluster name of the databases you want to upgrade.</p>
<p>e.g. if you&#8217;ve installed Postgresql 8.3 and have databases in 8.1, just run:</p>
<p><code># pg_upgradecluster 8.1 main</code></p>
<p>This upgrades the databases in the &#8220;main&#8221; cluster under version 8.1 and puts them under &#8220;main&#8221; in version 8.3.  If you already have a &#8220;main&#8221; cluster in 8.3, you&#8217;ll need to drop it first.</p>
<p>This little tool not only dumps and loads the database, but it also changes the config so 8.3 runs on the standard port previously used by 8.1 (or whatever your older version).  A painless way to upgrade.</p>
]]></content:encoded>
			<wfw:commentRss>http://scottbarnham.com/blog/2009/06/23/migrating-postgresql-databases-the-easy-way/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Gvim menu bar missing</title>
		<link>http://scottbarnham.com/blog/2009/03/09/gvim-menu-bar-missing/</link>
		<comments>http://scottbarnham.com/blog/2009/03/09/gvim-menu-bar-missing/#comments</comments>
		<pubDate>Mon, 09 Mar 2009 03:04:08 +0000</pubDate>
		<dc:creator>Scott</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://scottbarnham.com/blog/2009/03/09/gvim-menu-bar-missing/</guid>
		<description><![CDATA[I just opened gvim on my Ubuntu (Hardy Heron) box and found there was no menu bar (File, Edit, etc).
After messing with some guioptions and getting nowhere I ran gvim as root (using sudo) and the menu bar was there.  The answer came from a forum post by &#8220;Marko&#8221;:
Delete the file ~/.gnome2/Vim
It will be [...]]]></description>
			<content:encoded><![CDATA[<p>I just opened <code>gvim</code> on my Ubuntu (Hardy Heron) box and found there was no menu bar (File, Edit, etc).</p>
<p>After messing with some <code>guioptions</code> and getting nowhere I ran <code>gvim</code> as root (using <code>sudo</code>) and the menu bar was there.  The answer came from a forum post by &#8220;Marko&#8221;:</p>
<p>Delete the file <code>~/.gnome2/Vim</code></p>
<p>It will be recreated when you run <code>gvim</code> again.  With luck, the menu will be displayed again.</p>
]]></content:encoded>
			<wfw:commentRss>http://scottbarnham.com/blog/2009/03/09/gvim-menu-bar-missing/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Layoff Talent &#8211; Django project just launched</title>
		<link>http://scottbarnham.com/blog/2008/12/11/layoff-talent-django-project-just-launched/</link>
		<comments>http://scottbarnham.com/blog/2008/12/11/layoff-talent-django-project-just-launched/#comments</comments>
		<pubDate>Thu, 11 Dec 2008 17:05:48 +0000</pubDate>
		<dc:creator>Scott</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://scottbarnham.com/blog/2008/12/11/layoff-talent-django-project-just-launched/</guid>
		<description><![CDATA[Andrew and I spent a few days this week putting together a new Django project.
It&#8217;s called Layoff Talent and it&#8217;s a place for people in the tech industry who have been laid off and are looking for a new job.  They can add a simple profile and then hopefully be picked up by employers [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://twitter.com/andrewgleave">Andrew</a> and <a href="http://twitter.com/scottbarnham">I</a> spent a few days this week putting together a new Django project.</p>
<p>It&#8217;s called <a href="http://layofftalent.com/">Layoff Talent</a> and it&#8217;s a place for people in the tech industry who have been laid off and are looking for a new job.  They can add a simple profile and then hopefully be picked up by employers looking for new talent.</p>
<p>It&#8217;s similar in some ways to <a href="http://djangopeople.net/">Django People</a> or the <a href="http://djangogigs.com/">Djangogigs</a> developer listings, but specifically for people who have been laid off and not restricted to Django developers.</p>
<p>There&#8217;s nothing ground breaking from a development point of view, but it&#8217;s another example of how Django makes it easy to put out a full-featured site in a short time.  Of course, we&#8217;ll be adding more features as the site gets popular.</p>
<p>If you know someone who has been laid off, please tell them about <a href="http://layofftalent.com/">layofftalent.com</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://scottbarnham.com/blog/2008/12/11/layoff-talent-django-project-just-launched/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Get User from session key in Django</title>
		<link>http://scottbarnham.com/blog/2008/12/04/get-user-from-session-key-in-django/</link>
		<comments>http://scottbarnham.com/blog/2008/12/04/get-user-from-session-key-in-django/#comments</comments>
		<pubDate>Thu, 04 Dec 2008 20:43:42 +0000</pubDate>
		<dc:creator>Scott</dc:creator>
				<category><![CDATA[Django]]></category>

		<guid isPermaLink="false">http://scottbarnham.com/blog/2008/12/04/get-user-from-session-key-in-django/</guid>
		<description><![CDATA[Error emails contain session key
When you get an error email from your Django app telling you someone got a server error, it&#8217;s not always easy to tell which user had a problem.  It might help your debugging to know or you might want to contact the user to tell them you have fixed the [...]]]></description>
			<content:encoded><![CDATA[<h2>Error emails contain session key</h2>
<p>When you get an error email from your Django app telling you someone got a server error, it&#8217;s not always easy to tell which user had a problem.  It might help your debugging to know or you might want to contact the user to tell them you have fixed the problem.</p>
<p>Assuming the user is logged in when they get the error, the email will contain the session key for that user&#8217;s session.  The relevant part of the email looks like:</p>
<pre>&lt;WSGIRequest
GET:&lt;QueryDict: {}&gt;,
POST:&lt;QueryDict: {}&gt;,
COOKIES:{ 'sessionid': '8cae76c505f15432b48c8292a7dd0e54'},
...</pre>
<h2>Finding the user from the session</h2>
<p>If the session still exists we can find it, unpickle the data it contains and get the user id.  Here&#8217;s a short script to do just that:</p>
<pre>from django.contrib.sessions.models import Session
from django.contrib.auth.models import User

session_key = '8cae76c505f15432b48c8292a7dd0e54'

session = Session.objects.get(session_key=session_key)
uid = session.get_decoded().get('_auth_user_id')
user = User.objects.get(pk=uid)

print user.username, user.get_full_name(), user.email</pre>
<p>There it is.  Pass in the session key (sessionid cookie) and get back the user&#8217;s name and email address.</p>
<p><strong>Plug:</strong> Get your own job board at <a href="http://www.fuselagejobs.com/">Fuselagejobs</a></p>
]]></content:encoded>
			<wfw:commentRss>http://scottbarnham.com/blog/2008/12/04/get-user-from-session-key-in-django/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Dynamic upload paths in Django</title>
		<link>http://scottbarnham.com/blog/2008/08/25/dynamic-upload-paths-in-django/</link>
		<comments>http://scottbarnham.com/blog/2008/08/25/dynamic-upload-paths-in-django/#comments</comments>
		<pubDate>Mon, 25 Aug 2008 21:38:27 +0000</pubDate>
		<dc:creator>Scott</dc:creator>
				<category><![CDATA[Django]]></category>

		<guid isPermaLink="false">http://scottbarnham.com/blog/2008/08/25/dynamic-upload-paths-in-django/</guid>
		<description><![CDATA[For a while I&#8217;ve been using the CustomImageField as a way to specify an upload path for images.  It&#8217;s a hack that lets you use ids or slugs from your models in the upload path, e.g.:
/path/to/media/photos/1234/flowers.jpg
or
/path/to/media/photos/scotland-trip/castle.jpg
CustomImageField no more
Since the FileStorageRefactor was merged in to trunk r8244, it&#8217;s no longer necessary to use the custom [...]]]></description>
			<content:encoded><![CDATA[<p>For a while I&#8217;ve been using the <a href="http://scottbarnham.com/blog/2007/07/31/uploading-images-to-a-dynamic-path-with-django/">CustomImageField</a> as a way to specify an upload path for images.  It&#8217;s a hack that lets you use ids or slugs from your models in the upload path, e.g.:</p>
<p><code>/path/to/media/photos/1234/flowers.jpg</code><br />
or<br />
<code>/path/to/media/photos/scotland-trip/castle.jpg</code></p>
<h2>CustomImageField no more</h2>
<p>Since the <a href="http://code.djangoproject.com/wiki/FileStorageRefactor">FileStorageRefactor</a> was merged in to trunk <a href="http://code.djangoproject.com/changeset/8244">r8244</a>, it&#8217;s no longer necessary to use the custom field.  Other recent changes to trunk mean that it doesn&#8217;t work any more in its current state, so this is a good time to retire it.</p>
<h2>Pass a callable in <code>upload_to</code></h2>
<p>It is now possible for the <code>upload_to</code> parameter of the <code><a href="http://www.djangoproject.com/documentation/model-api/#filefield">FileField</a></code> or <code>ImageField</code> to be a callable, instead of a string.  The callable is passed the current model instance and uploaded file name and must return a path.  That sounds ideal.</p>
<p>Here&#8217;s an example:</p>
<pre>import os
from django.db import models

def get_image_path(instance, filename):
    return os.path.join('photos', instance.id, filename)

class Photo(models.Model):
    image = models.ImageField(upload_to=get_image_path)</pre>
<p><code>get_image_path</code> is the callable (in this case a function).  It simply gets the id from the instance of <code>Photo</code> and uses that in the upload path.  Images will be uploaded to paths like:</p>
<p><code>photos/1/kitty.jpg</code></p>
<p>You can use whatever fields are in the instance (slugs, etc), or fields in related models.  For example, if <code>Photo</code> models are associated with an <code>Album</code> model, the upload path for a <code>Photo</code> could include the <code>Album</code> slug.</p>
<p>Note that if you are using the id, you need to make sure the model instance was saved before you upload the file.  Otherwise, the id hasn&#8217;t been set at that point and can&#8217;t be used.</p>
<p>For reference, here&#8217;s what the main part of the view might look like:</p>
<pre>...
    if request.method == 'POST':
        form = PhotoForm(request.POST, request.FILES)
        if form.is_valid():
            photo = Photo.objects.create()
            image_file = request.FILES['image']
            photo.image.save(image_file.name, image_file)
...</pre>
<p>This is much simpler than the hacks used in <code>CustomImageField</code> and provides a nice flexible way to specify file or image upload paths per-model instance.</p>
<p><strong>Note:</strong> If you are using ModelForm, when you call <code>form.save()</code> it will save the file &#8211; no need to do it yourself as in the example above.</p>
]]></content:encoded>
			<wfw:commentRss>http://scottbarnham.com/blog/2008/08/25/dynamic-upload-paths-in-django/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Extending the Django User model with inheritance</title>
		<link>http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/</link>
		<comments>http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/#comments</comments>
		<pubDate>Thu, 21 Aug 2008 19:40:43 +0000</pubDate>
		<dc:creator>Scott</dc:creator>
				<category><![CDATA[Django]]></category>

		<guid isPermaLink="false">http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/</guid>
		<description><![CDATA[Extra fields for Users
Most of the Django projects I&#8217;ve worked on need to store information about each user in addition to the standard name and email address held by the contrib.auth.models.User model.
The old way: User Profiles
The solution in the past was to create a &#8220;user profile&#8221; model which is associated 1-to-1 with the user.  [...]]]></description>
			<content:encoded><![CDATA[<h2>Extra fields for Users</h2>
<p>Most of the Django projects I&#8217;ve worked on need to store information about each user in addition to the standard name and email address held by the <code>contrib.auth.models.User</code> model.</p>
<h2>The old way: User Profiles</h2>
<p>The solution in the past was to create a &#8220;user profile&#8221; model which is associated 1-to-1 with the user.  Something like:</p>
<h4>the model</h4>
<pre>class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True, related_name='profile')
    timezone = models.CharField(max_length=50, default='Europe/London')</pre>
<h4>config in <code>settings.py</code></h4>
<pre>AUTH_PROFILE_MODULE = 'accounts.UserProfile'</pre>
<h4>usage</h4>
<pre>profile = request.user.get_profile()
print profile.timezone</pre>
<p>It works ok, but it&#8217;s an extra database query for each request that uses the profile (it&#8217;s cached during the request so each call to <code>get_profile()</code> is not a query).  Also, the information about the user is stored in two separate models, so you need to display and update fields from both the <code>User</code> and the <code>UserProfile</code> models.</p>
<h2>The new way: Model Inheritance</h2>
<p>As part of the great work done on the <a href="http://code.djangoproject.com/wiki/QuerysetRefactorBranch">queryset-refactor</a> by <a href="http://www.pointy-stick.com/about/">Malcolm</a> et al, Django now has <a href="http://www.djangoproject.com/documentation/model-api/#model-inheritance">model inheritance</a>.</p>
<p>If you&#8217;re using trunk as of revision 7477 (26th April 2008), your model classes can inherit from an existing model class.  Additional fields are stored in a separate table which is linked to the table of the base model.  When you retrieve your model, the query uses a join to get the fields from it and the base model.</p>
<h3>Inheriting from User</h3>
<p>Instead of creating a User Profile class, why don&#8217;t we inherit from the normal <code>User</code> class and add some fields?</p>
<pre>from django.contrib.auth.models import User, UserManager

class CustomUser(User):
    """User with app settings."""
    timezone = models.CharField(max_length=50, default='Europe/London')

    # Use UserManager to get the create_user method, etc.
    objects = UserManager()</pre>
<p>Now each instance of <code>CustomUser</code> will have the normal <code>User</code> fields and methods, as well as our additional fields and methods.  Pretty handy, no?</p>
<p>We add <code>UserManager</code> as the default manager so that the standard methods are available.  In particular, to create a user, we really want to say:</p>
<pre>user = CustomUser.objects.create(...)</pre>
<p>If we just created the user from the <code>User</code> class, we wouldn&#8217;t get a row in the <code>CustomUser</code> table.  Creation needs to be done in the derived class.</p>
<p>You can still get and update the underlying <code>User</code> model, no problem, but it won&#8217;t have the additional fields and methods found in our <code>CustomUser</code> class.</p>
<h2>Getting the <code>CustomUser</code> class by default</h2>
<p>So far, there&#8217;s one problem.  When you get <code>request.user</code>, it&#8217;s an instance of <code>User</code>, not an instance of <code>CustomUser</code>, so you don&#8217;t get the extra fields and methods.</p>
<p>What we want is for Django to retrieve the <code>CustomUser</code> instance transparently.  It turns out to be quite easy.</p>
<h3>Users come from authentication backends</h3>
<p>The default authentication backend gets the <code>User</code> model from the database, checks the password is correct then returns the <code>User</code>.  You can <a href="http://www.djangoproject.com/documentation/authentication/#writing-an-authentication-backend">write your own authentication backend</a>, for example to check the username and password against some other data source or to use the email address instead of username.</p>
<p>In our case, we can use an authentication backend to return an instance of <code>CustomUser</code> instead of <code>User</code>.</p>
<h4>the authentication backend in <code>auth_backends.py</code></h4>
<pre>from django.conf import settings
from django.contrib.auth.backends import ModelBackend
from django.core.exceptions import ImproperlyConfigured
from django.db.models import get_model

class CustomUserModelBackend(ModelBackend):
    def authenticate(self, username=None, password=None):
        try:
            user = self.user_class.objects.get(username=username)
            if user.check_password(password):
                return user
        except self.user_class.DoesNotExist:
            return None

    def get_user(self, user_id):
        try:
            return self.user_class.objects.get(pk=user_id)
        except self.user_class.DoesNotExist:
            return None

    @property
    def user_class(self):
        if not hasattr(self, '_user_class'):
            self._user_class = get_model(*settings.CUSTOM_USER_MODEL.split('.', 2))
            if not self._user_class:
                raise ImproperlyConfigured('Could not get custom user model')
        return self._user_class</pre>
<h4>config in <code>settings.py</code></h4>
<pre>AUTHENTICATION_BACKENDS = (
    'myproject.auth_backends.CustomUserModelBackend',
)
...

CUSTOM_USER_MODEL = 'accounts.CustomUser'</pre>
<p>That&#8217;s it.  Now when you get <code>request.user</code>, it&#8217;s an instance of the <code>CustomUser</code> class with whatever additional fields or methods you have added.</p>
<p>P.S. Looking for Django hosting?  I&#8217;d recommend <a href="http://www.webfaction.com/shared_hosting?affiliate=sgb79">WebFaction</a> for shared hosting and <a href="https://manage.slicehost.com/customers/new?referrer=107490507">Slicehost</a> for a VPS.</p>
]]></content:encoded>
			<wfw:commentRss>http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/feed/</wfw:commentRss>
		<slash:comments>60</slash:comments>
		</item>
		<item>
		<title>Django performance testing &#8211; a real world example</title>
		<link>http://scottbarnham.com/blog/2008/04/28/django-performance-testing-a-real-world-example/</link>
		<comments>http://scottbarnham.com/blog/2008/04/28/django-performance-testing-a-real-world-example/#comments</comments>
		<pubDate>Mon, 28 Apr 2008 13:58:55 +0000</pubDate>
		<dc:creator>Scott</dc:creator>
				<category><![CDATA[Django]]></category>
		<category><![CDATA[httperf]]></category>
		<category><![CDATA[profiling]]></category>

		<guid isPermaLink="false">http://scottbarnham.com/blog/2008/04/28/django-performance-testing-a-real-world-example/</guid>
		<description><![CDATA[About a week ago Andrew and I launched a new Django-powered site called Hey! Wall.  It&#8217;s a social site along the lines of &#8220;the wall&#8221; on social networks and gives groups of friends a place to leave messages, share photos, videos and links.
We wanted to gauge performance and try some server config and code [...]]]></description>
			<content:encoded><![CDATA[<p>About a week ago <a href="http://tangerinesmash.com/">Andrew</a> and <a href="http://www.staplefish.com/">I</a> launched a new Django-powered site called <a href="http://heywall.com/">Hey! Wall</a>.  It&#8217;s a social site along the lines of &#8220;the wall&#8221; on social networks and gives groups of friends a place to leave messages, share photos, videos and links.</p>
<p>We wanted to gauge performance and try some server config and code changes to see what steps we could take to improve it.  We tested using <code>httperf</code> and doubled performance by making some optimisations.</p>
<h3>Server and Client</h3>
<p>The server is a <a href="https://manage.slicehost.com/customers/new?referrer=107490507">Xen VPS from Slicehost</a> with 256MB RAM running Debian Etch.  It is located in the US Midwest.</p>
<p>For testing, the client is a <a href="http://www.xtrahost.net/xenvps/">Xen VPS from Xtraordinary Hosting</a>, located in the UK.  Our normal Internet access is via ADSL which makes it difficult to make enough requests to the server.  Using a well-connected VPS as the client means we can really hammer the server.</p>
<h4>Server spec caveats</h4>
<p>It&#8217;s hard to say exactly what the server specs are.  The VPS has 256MB RAM and is hosted with similar VPSes, probably on a <a href="http://www.slicehost.com/questions/#users">quad core server with 16GB RAM</a>.  That&#8217;s a maximum of 64 VPSes on the physical server, assuming it is full of 256MB slices.  If the four processors are 2.4GHz, that&#8217;s 9.6GHz total, divided by 64 gives a minimum of 150MHz of CPU.</p>
<p>On a Xen VPS, you get a fixed allocation of memory and CPU without contention, but usually any <a href="http://www.slicehost.com/questions/#cpu-scheduling">available CPU on the machine can be used</a>.  If other VPSes on the same box are idle, your VPS can make use of more of the CPU.  This probably means more CPU was used during testing and perhaps more for some tests than for others.</p>
<h3>Measuring performance with httperf</h3>
<p>There are various web performance testing tools around including <a href="http://httpd.apache.org/docs/2.0/programs/ab.html">ab (from Apache)</a>, <a href="http://httpd.apache.org/test/flood/">Flood</a> and <a href="http://www.hpl.hp.com/research/linux/httperf/">httperf</a>.  We went with httperf for no particular reason.</p>
<p>An httperf command looks something like:</p>
<pre>httperf --hog --server=example.com --uri=/ --timeout=10 --num-conns=200 --rate=5</pre>
<p>In this example, we&#8217;re requesting <code>http://example.com/</code> 200 times, with up to 5 requests per second.</p>
<h3>Testing Plan</h3>
<p>Some tools support sessions and try to emulate users performing tasks on your site.  We went with a simple brute-force test to get an idea of how many requests per second the site could handle.</p>
<p>The basic approach is to make a number of requests and see how the server responds: a status 200 is good, a status 500 is bad.  Increase the rate (the number of requests made per second) and try again.  When it starts returning lots of 500s, you&#8217;ve reached a limit.</p>
<h4>Monitoring server resources</h4>
<p>The other side is knowing what the server is doing in terms of memory and CPU use.  To track this, we run <code>top</code> and log the output to a file for later review.  The top command is something like:</p>
<pre>top -b -d 3 -U www-data > top.txt</pre>
<p>In this example we&#8217;re logging information on processes running as user <code>www-data</code> every three seconds.  If you want to be more specific, instead of <code>-U username</code> you can use <code>-p 1, 2, 3</code> where 1, 2 and 3 are pids (process ids of processes you want to watch).</p>
<p>The web server is Lighttpd with Python 2.5 running as FastCGI processes.  We didn&#8217;t log information on the database process (PostgreSQL), though that could be useful.</p>
<p>Another useful tool is <code>vmstat</code>, particularly the swap columns which show how much memory is being swapped.  Swapping means you don&#8217;t have enough memory and is a performance killer.  To repeatedly run <code>vmstat</code>, specify the number of seconds between checks.  e.g.</p>
<pre>vmstat 2</pre>
<h4>Authenticated requests with httperf</h4>
<p><code>httperf</code> makes simple <code>GET</code> requests to a URL and downloads the html (but not any of the media).  Requesting public/anonymous pages is easy, but what if you want a page that requires login?</p>
<p><code>httperf</code> can pass request headers.  Django authentication (from <code>django.contrib.auth</code>) uses sessions which rely on a session id held in a cookie on the client.  The client passes the cookie in a request header.  You see where this is going.</p>
<p>Log in to the site and check your cookies.  There should be one like <code>sessionid=97d674a05b2614e98411553b28f909de</code>.  To pass this cookie using httperf, use the <code>--add-header</code> option.  e.g.</p>
<pre>httperf ... --add-header='Cookie: sessionid=97d674a05b2614e98411553b28f909de\n'</pre>
<p>Note the <code>\n</code> after the header.  If you miss it, you will probably get timeouts for every request.</p>
<h4>Which pages to test</h4>
<p>With this in mind we tested two pages on the site:</p>
<ol>
<li><strong>home</strong>: anonymous request to the home page</li>
<li><strong>wall</strong>: authenticated request to a &#8220;wall&#8221; which contains content retrieved from the database</li>
</ol>
<h3>Practically static versus highly dynamic</h3>
<p>The home page is essentially static for anonymous users and just renders a template without needing any data from the database.</p>
<p>The wall page is very dynamic, with the main data retrieved from the database.  The template is rendered specifically for the user with dates set to the user&#8217;s timezone, &#8220;remove&#8221; links on certain items, etc.  The particular wall we tested has about 50 items on it and before optimisation made about 80 database queries.</p>
<p>For the first test we had two FastCGI backends running, able to accept requests for Django.</p>
<p>Home: 175 req/s (i.e. requests per second).<br />
Wall: 8 req/s.</p>
<h3>Compressed content</h3>
<p>The first config optimisation was to enable gzip compression of the output using <code>GZipMiddleware</code>.  Performance improved slightly, but not a huge difference.  Worth doing for the bandwidth savings in any case.</p>
<p>Home: 200 req/s.<br />
Wall: 8 req/s.</p>
<h3>More processes, shorter queues</h3>
<p>Next we increased the number of FastCGI backends from two to five.  This was an improvement with fewer 500 responses as more of the requests could be handled by the extra backends.</p>
<p>Home: 200 req/s.<br />
Wall: 11 req/s.</p>
<h3>Mo processes, mo problems</h3>
<p>The increase from two to five was good, so we tried increasing FastCGI backends to ten.  Performance <em>decreased</em> significantly.</p>
<p>Checking with <code>vmstat</code> on the server, I could see it was swapping.  Too many processes, each using memory for Python, had caused the VPS to run out of memory and swap memory to and from disk.</p>
<p>Home: 150 req/s.<br />
Wall: 7 req/s.</p>
<p>At this point we set the FastCGI backends back down to five for further tests.</p>
<h3>Profiling &ndash; where does the time go</h3>
<p>The wall page had disappointing performance, so we started to optimise.  The first thing we did was profile the code to see where time was being spent.</p>
<p>Using some simple <a href="http://www.djangosnippets.org/snippets/727/">profiling middleware</a> it was clear the time was being spent in database queries.  The wall page had a lot of queries and they increased linearly with the number of items on the wall.  On the test wall this caused around 80 queries.  No wonder its performance was poor.</p>
<h3>Optimise this</h3>
<p>By optimising how media attached to items is handled we were able to drop one query per item straight away.  This slightly reduced how long the request took and so increased the number of queries handled per second.</p>
<p>Wall: 12 req/s.</p>
<p>Another inefficiency was the way several filters were applied to the content of each item whenever the page was requested.  We changed it so the html output from the filtered content was stored in the item, saving some processing each time the page was viewed.  This gave another small increase.</p>
<p>Wall: 13 req/s.</p>
<p>Back to reducing database queries, we were able to eliminate one query per item by changing how user profiles were retrieved (used to show who posted the item to the wall).  Another worthwhile increase came from this change.</p>
<p>Wall: 15 req/s.</p>
<p>The final optimisation for this round of testing was to further reduce the queries needed to retrieve media attached to items.  Again, we shed some queries and slightly increased performance.</p>
<p>Wall: 17 req/s.</p>
<h3>Next step: caching</h3>
<p>Having reduced queries as much as we can, the next step would be to do some caching.  Retrieving cached data is usually much quicker than hitting the database, so we&#8217;d expect a good increase in performance.</p>
<p>Caching the output of complete pages is not useful because each page is heavily personalised to the user requesting it.  It would only be a cache hit if the user requested the same page twice with nothing changing on it in the meantime.</p>
<p>Caching data such as lists of walls, items and users is more useful.  The cached data could be used for multiple requests from a single user and shared to some degree across walls and different users.  It&#8217;s not necessarily a huge win because each wall is likely to have a very small number of users, so the data would need to stay in cache long enough to be retrieved by others.</p>
<p>Our simplistic <code>httperf</code> tests would be very misleading in this case.  Each request is made as the same user so cache hits would be practically 100% and performance would be great!  This does not reflect real-world use of the site, so we&#8217;d need some better tests.</p>
<p>We haven&#8217;t made use of caching yet as the site can easily handle its current level of activity, but if <a href="http://heywall.com/">Hey!&nbsp;Wall</a> becomes popular, it will be our next step.</p>
<h3>How many users is 17 req/s?</h3>
<p>Serving 17 req/s still seems fairly low, but it would be interesting to know how this translates to actual users of the site.  Obviously, this figure doesn&#8217;t include serving any media such as images, CSS and JavaScript files.  Media files are relatively large but should be served fast as they are handled directly by Lighttpd (not Django) and have <code>Expires</code> headers to allow the client to cache them.  Still, it&#8217;s some work the server would be doing in addition to what we measured with our tests.</p>
<p>It&#8217;s too early to tell what the common usage pattern would be, so I can only speculate.  <em>Allow me to do that!</em></p>
<p>I&#8217;ll assume the average user has access to three walls and checks each of them in turn, pausing for 10 or 20 seconds on each to read new comments and perhaps view some photos or open links.  The user does this three times per day.</p>
<p>Looking specifically at the wall page and ignoring media, that means our user is making 9 requests per day for wall pages.  Each user only makes one request at a time, so 17 users can be doing that at any second in time.  Within a minute the user only makes three requests so is only counted within the 17 concurrent users for 3 seconds out of 60 (or 1 in 20).</p>
<p>If the distribution of user requests over time was perfectly balanced (hint: it won&#8217;t be), that means 340 users (17 * 20) could be using the site each minute.  To continue with this unrealistic example, we could say there are 1440 minutes in a day and each user is on the site for three minutes per day, so the site could handle about 163,000 users.  That would be very good for a $20/month VPS!</p>
<p>To reign in those numbers a bit, lets say we handle 200 concurrent users in a minute for 6 hours per day, 100 concurrent users for another 6 hours and 10 concurrent users for the remaining 12 hours.  That&#8217;s still around 115,000 users the site could handle in a day given the maximum load of 17 requests per second.</p>
<p>I&#8217;m sure these numbers are somewhere between unrealistic and absurd.  I&#8217;d be interested in comments on better ways to estimate or any real-world figures.</p>
<h3>What we learned</h3>
<p>To summarise:</p>
<ol>
<li>Testing the performance of your website may yield surprising results</li>
<li>Having many database queries is bad for performance (duh)</li>
<li>Caching works better for some types of site than others</li>
<li>An inexpensive VPS may handle a lot more users than you&#8217;d think</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://scottbarnham.com/blog/2008/04/28/django-performance-testing-a-real-world-example/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic Page Served (once) in 0.337 seconds -->
<!-- Cached page served by WP-Cache -->
