Categories
Django Python

Up and Running with Django 1.4

As with any new web framework, getting started can seem daunting. Even though Django has some of best documentation of any framework, it can still be a pain to figure out how things work. The goal of this post is to help you, the Django newcomer, get up an running with a simple blog.

Step 1: Your Environment

One thing that isn’t clearly stated in most tutorials is that how you set up your environment can either make or break your Django experience. To make your Django experience as easy as possible, you’ll need to make sure that you have two packages installed: virtualenv and virtualenvwrapper
Virtualenv can be installed using pip, and virtualenvwrapper can be installed by following the instructions on it’s site. Once you have both of these installed, you’re going to create something called a virtual environment. A virtual environment allows you to install any packages you need for your Django development without having it interfere with the rest of your system. It also allows you to create a requirements file, which allows other people to replicate your environment. To get started, we use the mkvirtualenv command.

mkvirtualenv myblog

If you at some point close your terminal window and want to load your virtual environment again you can use the workon command.

workon myblog

If by chance you don’t want to work on this environment any more, you use the deactivate command.

deactivate

So bringing it all together, we’re going to create an environment, create a directory to play around in, and then install django.

cd ~/Desktop
mkvirtualenv myblog
mkdir blog
pip install django

Step 2: Create a Django Project

Now that we have our environment set up we need to create our first project. We’re going to call it “blog”.

cd blog
django-admin.py startproject blog .

If you look in the blog directory now, you’ll see two things: a folder named blog and a file named manage.py. The manage.py file is used to administer your project. Using it you’ll sync model changes, run the server, and collect static assets. So why don’t we try running the server?

chmod +x manage.py
./manage.py runserver

The first line allows the file to be executed, and the second line starts the server. Once the second line is executed you should see the following:

(myblog)jack@jack-HP-HDX-16-Notebook-PC:~/Desktop/blog$ chmod +x manage.py
(myblog)jack@jack-HP-HDX-16-Notebook-PC:~/Desktop/blog$ ./manage.py runserver
Validating models...

0 errors found
Django version 1.4, using settings 'blog.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Once your development server is running, any changes you make to your files will be noticed and served automatically. If you check out the address that the server is running at, you should see this:

Step 3: Configuring a database

If we’re going to create a blog, we need to be able to store information. To do that, and database is required. In the newly create blog folder, there is a file called settings.py. That file is where we configure our server and add any apps we create. First things first though, we need a database. The Django ORM does a great job of abstracting out the database layer for us, so we can plug in basically any database that we want. For the sake of simplicity, we’re going to use SQLite. To create a SQLite database, make sure that you have the SQLite3 package installed on your operating system. Make sure you are in the same folder as the settings.py file, and then execute the following commands:

sqlite3 blog.db
sqlite> .tables #Look ma, no tables in here!
sqlite> .q #quit

Now that you have a database configured, you can crack open the settings.py file and change this bit of code:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.',
        'NAME': '',
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
    }
}

to this:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'blog.db',
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
    }
}

Now that your Django project knows about your database, you need to have it create some tables for you. Go back to the directory with manage.py in it and run:

./manage.py syncdb

Once you run syncdb, you’ll get some output that looks like this:

./manage.py syncdb
Creating tables ...
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_user_permissions
Creating table auth_user_groups
Creating table auth_user
Creating table django_content_type
Creating table django_session
Creating table django_site

You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): yes
Username (leave blank to use 'jack'): 
E-mail address: jack.slingerland@gmail.com
Password: 
Password (again): 
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)

Step 4: The Posts App

A Django powered website consists of many smaller “apps”. For instance, a blog may have a posts app and a photo app. The idea is that things that aren’t concerned with each other (photos,posts) should be separate entities. For our blog projects we’re going to only use one app, and we’ll call it posts.
Creating an app is easy. As usual, Django does most of the work for you so you don’t get bogged down writing a bunch of tedious boilerplate code. Navigate back to the top of your Django project (the directory with manage.py in it) and do the following:

./manage.py startapp posts

If you check out your project now, you’ll see a new directory called posts. If you descend into that directory, you’ll see 4 files.

  • __init__.py: Let’s Python know that this directory is a package. This has more uses, but it’s beyond the scope of this post.
  • models.py: We define how our models (tables) should look and act.
  • views.py: This is where we grab data from out model, massage it to our needs, and then render it to a template.
  • tests.py: Unit tests go here.

Just because the app is created, doesn’t mean that Django recognizes it. You actually have to add the app to the INSTALLED_APPS section of the settings.py file. To do that, add a line to the end of the INSTALLED_APPS list.

'posts', # Don't forget the trailing comma!

Step 5: The Post Model

We’re finally to the part where we get to write code! But before we dive in, we need to think about what a blog post actually is. It will generally contain content, a title, and posted on date. With that in mind, open posts/models.py in your editor and add the following:

class Post(models.Model):
	title = models.CharField(max_length=100)
	content = models.TextField()
	post_date = models.DateTimeField(auto_now=True)

Once you’ve added those, save the file and then go back to manage.py and run syncdb. You should get some output that looks like:

./manage.py syncdb
Creating tables ...
Creating table posts_post
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)

If we hadn’t added the posts app to our settings.py file, the syncdb command wouldn’t have generated our table for us.

Step 5: The Admin

One of the best parts about Django is it’s free admin interface that you get. The admin isn’t enabled by, but it’s pretty easy to set up. First off, we need to open settings.py and uncomment two lines.

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    'django.contrib.admindocs',
    'posts',
)

As the comments say, uncomment the lines that say “django.contrib.admin” and “django.contrib.admindocs”. The admindocs line isn’t necessary, but it’s nice for completeness. The second step is to set up the url configuration for the admin. Go to your urls.py file and make it look like this:

from django.conf.urls import patterns, include, url
 
from django.contrib import admin
admin.autodiscover()
 
urlpatterns = patterns('',
 
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    url(r'^admin/', include(admin.site.urls)),
)

Now that the admin is enabled, we need to add our model to it. In the blog app folder (same folder as models.py), create a file called admin.py and put the following in it:

from posts.models import Post
from django.contrib import admin
 
admin.site.register(Post)

All this does is let the admin know that it can manage your model for you. Since you technically added a new app (the admin app), you’ll need to run syncdb again.

./manage.py syncdb
Creating tables ...
Creating table django_admin_log
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)

Go ahead an start the server again, and go to the admin. It should be located at http://127.0.0.1:8000/admin/. You’ll be presented with a login screen, with which you’ll use the credentials you entered in the initial setup. Once you’re logged in, you’ll see this:

Now that you can see the Posts model in the admin, click the “add” button next to it. When you do, you’ll see a form like this.

Enter a title and some content, and then click “Save and Add Another”. Enter another title a and some content, and then click “Save”. You’ll be presented with a screen with two entries on it, that both say “Post object”.

Now, “Post object” doesn’t do a very good job of describing your post. What if you want to edit it? You won’t know what is in each post until you click into it. To fix that, go to models.py and modify your Post model to look like this:

class Post(models.Model):
	title = models.CharField(max_length=100)
	content = models.TextField()
	post_date = models.DateTimeField(auto_now=True)
 
	def __unicode__(self):
		return self.title

Now when you view your post list, you’ll see the post titles instead of “Post object”.

Step 6: URLconfs

We now have a few posts in the database and can edit them in the Django admin. The next step is to set up our url structure that will allow users to view the posts on the front end of the site. Open urls.py and add the lines to it that have the “#Added” comment at the end of them.

from django.conf.urls import patterns, include, url
 
from django.contrib import admin
admin.autodiscover()
 
from posts.views import * #added
 
urlpatterns = patterns('',
    ('^$', home), #added
    (r'^post/(?P<post_id>\d+)/$',post_specific), #added
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    url(r'^admin/', include(admin.site.urls)),
)

The first line added tells Python about your views (we’ll get to them next). The 2nd and 3rd lines added specify how certain urls are handled. The 2nd added line defines your home URLconf, and the 3rd added line defined your route for specific posts. Next, open yours posts/views.py file and add the following:

from django.shortcuts import render_to_response
from django.http import Http404
from posts.models import Post
 
def home(request):
	return render_to_response("home.html",{
		"posts" : Post.objects.all().order_by('post_date')
	})
 
def post_specific(request, post_id):
	try:
		p = Post.objects.get(pk=post_id)
	except:
		raise Http404
 
	return render_to_response("post_specific.html",{
		"post" : p
	})

In the first few lines we import some things we’ll need:

  • The ability to raise a 404 error.
  • Our Post model
  • A shortcut for rendering templates

The two functions we created are pretty straight forward. The home function takes all of the posts, and sends them to the “home.html” template where they will be rendered. The post_specific function checks to see if the post id that is passed in exists. If it does, it grabs that post and sends it on to the template. If it doesn’t, it raises a 404 error. Now, we need to make those templates.

Step 7: Templates

Creating templates is honestly the easiest part of the whole process. In your settings.py file, there is a variable called TEMPLATE_DIRS. You need to add the path to your templates folder in there. For instance, I created a folder called “templates” at the top level of my Django app, so mine looks like:

TEMPLATE_DIRS = (
    '/home/jack/Desktop/blog/templates',
)

Now in your templates directory, create home.html and post_specific.html. In home.html put the following:

<html>
	<head>
		<title>All posts!</title>
	</head>
	<body>
		<ol>
			{% for p in posts %}
			<li><a href='/post/{{ p.id }}'>{{ p.title }}</a></li>
			{% endfor %}
		</ol>
	</body>
</html>

and in post_specific.html put:

<html>
	<head>
		<title>{{ post.title }}</title>
	</head>
	<body>
		{{ post.content }}
		<p />
		<a href='/'>Back</a>
	</body>
</html>

Once everything is saved, go to http://127.0.0.1:8000 and check out your (simple) blog!

Next Steps

This is a very simplified tutorial. The goal is to help someone get started with something easy without getting bogged down in details. One of the greatest things about Django though is that the more details you learn, the greater it gets. With that in mind, I highly suggest checking out the following sites for more learning. Good luck!

  1. https://docs.djangoproject.com/en/1.4/ – The official Django documentation. Django has some of the best documentation out of any open source project, so don’t be scared of diving in. Be sure to check out the 4 part tutorial It covers some of the same things I did, but in much greater detail.
  2. http://www.djangobook.com/en/2.0/ – A lot of the material in the DjangoBook website is out of date, but it does a great job explaining some key concepts that are still relevant.
  3. http://www.reddit.com/r/django – The Django sub-Reddit is a great place to keep up with Django news and conversations.
  4. http://originalhaters.com/2012/07/30/mountain-lion-mamp-and-django-1-4/ – A great piece on getting Django up and running on Mountain Lion
Categories
Other Programming

Methods & Properties with Javascript OOP

Note: This isn’t quite OOP. It’s actually called the “module pattern”.

If you come from a language such as Python, PHP, or Java, you’re used to having public and private methods and variables. In Javascript this is possible too, but it’s not nearly as straight-forward. To make this happen, you usually need to wade through Javascript’s prototype inheritance. However, there is another way.

Step 1: Create your class.

function MyClass(somevar) {
}

Now that your class is created, you can instantiate an instance of it by doing the following:

var x = new MyClass(123);

Step 2: Public Methods and Properties

To expose properties and methods to the public, you need to attach them to an object and return it. Some people will attach to this, but I prefer to create a new object called self and return that. It keeps me from getting confused with what this scope I’m in. One thing to remember, is that anything inside of your class that isn’t in a function gets executed as soon as you create a new instance of it.

function MyClass(somevar) {
	var self = {};
 
	// Check to make sure somevar is defined and then
	// assign it to the my_property public property.
	if(somevar === undefined) { somevar = false; }
	self.my_property = somevar;
 
	// A public method!
	self.alert_loop = function(count) {
		if(count === undefined) { count = 1; }
		for(var i = 0; i < count; i++) {
			alert(self.my_property);
		}
	};
 
	return self;
}

You’ll see that we have two things exposed here: my_property and alert_loop. To access them, do this:

var x = new MyClass("Hi!");
alert(x.my_property); // Alerts "Hi!"
x.alert_loop(2); // Alerts "Hi!" twice

Step 3: Private Methods and Variables

Creating private methods and variables is very easy using this method Javascript OOP. All you do is not attach the variable or method to the self object.

function MyClass(somevar) {
	var self = {};
 
	/* Private */
	var loop_max = 2;
	function add_numbers(x,y) {
		return x + y;
	}
 
	/* Public stuff */
 
	if(somevar === undefined) { somevar = false; }
	self.my_property = somevar;
 
	self.alert_loop = function(count) {
		if(count === undefined) { count = 1; }
		for(var i = 0; i < count; i++) {
			alert(self.my_property);
		}
	};
 
	self.alert_numbers = function() {
		for(var i = 0; i < loop_max; i++) {
			alert(add_numbers(i,i+1));
		}
	};
 
	return self;
}

And to use it:

var x = new MyClass("Hi!");
x.add_numbers(1,2); // Will fail.
alert(x.loop_max);  // Will fail.
x.alert_numbers();  // works!

Conclusion

That’s it! Using this style of OOP in Javascript is easy to learn and easy to understand. If you have any questions, drop a comment and I’ll get back to you.

Categories
Other

Using Git with Subversion(SVN) on a Non-Standard Repository Layout

For the longest time I was a loyal Subversion(SVN) user. I know, it’s crazy, but I was. When I found out about Git, I was hooked immediately and used it for all of my personal projects. The problem was that at work we use SVN, and getting everyone to migrate to Git just wasn’t in the cards. Much to my surprise, Git has the ability to interact with a SVN repository, so I could still use it anyways.

The issue with my work’s current SVN layout is that it is non-standard. By that I mean all projects exist in one big happy repository. Something like:

Repository -> Project -> Trunk/Branches/Tags

Unfortunately, Git+SVN isn’t really all that excited about working with non-standard repositories, so I had to do some experimentation and Googling to figure it all out. Eventually, I came up with the following steps:

Step 1: Clone the Repo
The first step in this process is actually cloning your SVN repository. By clone, we mean make a full copy of it and all of the revision history.

git svn clone svn://the.svn.server/allEncompassingRepo/project -trunk=trunk/ .

After the initial clone is complete, we move to fixing where git should look for things.

Step 2: Set up fetch, branches, and tags
The initial setup for fetch, branches, and tags gets screwed up at this point if you have a non-standard layout like my employer does, so we need to do some cleanup. Open .git/config and set the following:

url = svn://the.svn.server/allEncompassingRepo
fetch = project/trunk:refs/remotes/trunk
branches = project/branches/*:refs/remotes/*
tags = project/tags/*:refs/remotes/tags/*

Now that the config file is all set, go ahead and save.

Step 3: Pull down your files
The config file is all set, so you’re ready to do your first pull.
git svn fetch svn
That’s all there is to it. If you’d like to know how to use Git+SVN, I suggest reading the fine article over at Viget.

Categories
Other Programming

Using JSHint with Sublime Text 2

Awhile ago I was looking an editor that was cross platform, light weight, and awesome. I’d dabbled with Netbeans in the past, but found it to be a little heavy for what I needed it for. I ended up settling on Sublime Text 2. I have a hard time coming up with words for how awesome Sublime Text 2 is, so here’s a screenshot of my current window.

JSHint

One of the languages I find myself writing frequently is Javascript. As most of you know, Javascript has an assortment of odd conventions that can be pretty hard to remember. Code quality checkers like JSLint and JSHint exist for this reason. Prior to Sublime Text 2 I never bothered integrating either of those tools into my editor, but found myself needing to streamline my development process.

Sublime Text 2 provides an easy way to write build systems depending on which language you’re using. The sublime-jshint plugin takes advantage of this. All you do to make this work is go to the sublime-jshint GitHub page, and follow the instructions. Once it’s installed, run CTRL+B (CMD+B on Mac) while inside a Javascript file and you should see output like this.

Categories
jQuery

Creating jQuery Plugins

Update: I was able to get permission to release the iScroll plugin! Check it out here.

Not too long ago I decided to write a jQuery plugin for making the use of iScroll a little less painful. Since I made the plugin at work I’m not really at liberty to share it. But what I can share is a step by step tutorial for creating a jQuery plugin of your own. Let’s get started.

Step 1: Scope

If you’ve been writing Javascript with jQuery for any amount of time, you find out pretty quickly that proper scoping is very important. You also learn that the $ symbol isn’t reliable. So what’s a coder to do? Make sure that your scope is contained within an anonymous function, and that you pass the jQuery object into that function.

(function($) {
	console.log($(document).jquery);
})(jQuery);

If you paste this code into your console (assuming jQuery is included), you should receive a print out of what version of jQuery you’re using.

Step 2: Functions

Now that you have the basic wrapper written, we need to write some real code. Before we start, there are 3 things you need to know.

  1. Functions are attached to the $.fn object.
  2. There may be more than one element passed into your function (plugin)
  3. We want to keep the chain alive if possible. (See jQuery Chaining if you have questions)

So, let’s write a function that adds the class “bob” to every item in the set. Yes, we could just use the .addClass() method, but then we wouldn’t need to write a plugin would we?

(function($) {
	$.fn.addBob = function() {  //Add the function
		return this.each(function() { //Loop over each element in the set and return them to keep the chain alive.
			var $this = $(this);
			$this.addClass("bob");
		});
	};
})(jQuery);

Step 3: Options

So let’s say you need to pass some options to your plugin. You know, like Bob’s last name, or if we should remove Bob. To accomplish this, all you do is create a defaultOptions object and load it with defaults. Then you use the $.extend function to overwrite it’s values with values passed in as a function parameter.

(function($) {
	$.fn.addBob = function(customOptions) {  //Add the function
		var options = $.extend({}, $.fn.addBob.defaultOptions, customOptions);
		return this.each(function() { //Loop over each element in the set and return them to keep the chain alive.
			var $this = $(this);
 
			//Determine what name to use.
			var name = "";
			if(options.lastName != "") {
				name = "bob-" + options.lastName;
			} else {
				name = "bob";
			}
 
			//Are we removing items?
			if(options.remove) {
				$this.removeClass(name);
			} else {
				$this.addClass(name);
			}
		});
	};
 
	$.fn.addBob.defaultOptions = {
		lastName : "",
		remove : false	
	};
})(jQuery);

Step 4: Running your plugin

Now that you’ve written your plugin, you need to run it!
Before

<ol id='x'>
	<li></li>
	<li></li>
</ol>
<ol id='y'>
	<li></li>
	<li></li>
</ol>

JS

	$("#x li, #y li").addBob({lastName: "awesome"});

After

<ol id='x'>
	<li class='bob-awesome'></li>
	<li class='bob-awesome'></li>
</ol>
<ol id='y'>
	<li class='bob-awesome'></li>
	<li class='bob-awesome'></li>
</ol>

JS

	$("#y li").addBob({lastName: "awesome", remove: true});

After

<ol id='x'>
	<li class='bob-awesome'></li>
	<li class='bob-awesome'></li>
</ol>
<ol id='y'>
	<li></li>
	<li></li>
</ol>

That’s all there is to it. If you have any questions, leave a comment and I’ll get back to you as soon as I can.

Categories
jQuery

jQuery Chaining

jQuery is the jewel in the crown that is web development. Once you discover it, Javascript is no longer a chore to write, hell, it might even be considered fun! Sure being able to select elements by ID, class, or type is great, but what about all the other stuff? What about chaining? I’ve heard such great stuff about it!

Chaining

The first thing you need to know about chaining is that you chain actions on to collections. A collection is what is returned when you select something using jQuery.

$("input");  //Collection of all input elements on the page.

When most people start using jQuery, they do something like this:

$("input").val("123");
$("input").addClass("awesome");
$("input").attr("data-bind", "15");

Yes, this code will work, but it’s inefficient. Every time you perform a selection, jQuery must traverse the DOM and find all the input elements. If you use chaining, it will simply use the collection of input elements that it already has.

$("input")
	.val("123")
	.addClass("awesome")
	.attr("data-bind", "15");

So why does this work? Because each method that you call in the chain returns the collection. So in this case “val()”, “addClass()”, and “attr()” all return “$(input)”. However, not all methods support chaining. For instance, the “text()” method breaks the chain, so if you’re going to use it, do it at the end.
What if you want to keep the chain alive though? No problem. You can simply back-out of the destructive action using the “end()” method.

Before

<ol id='mylist'>
	<li>
	</li>
	<li>
	</li>
	<li>
	</li>
</ol>

Javascript

$('#mylist')
	.find('>li')
		.filter(':last')
			.addClass('Meow')
		.end()
		.filter(':first')
			.addClass('Mix')
		.end()
		.addClass('catfood')
	.end()
	.addClass('thelist');

After

<ol id='mylist' class='thelist'>
	<li class='Mix catfood'>
	</li>
	<li class='catfood'>
	</li>
	<li class='Meow catfood'>
	</li>
</ol>

While sometimes confusing, you can see that chaining is often the most efficient way to handle modifying the DOM.

Writing Chainable Plugins/Functions

Now that you know all about chaining, you’ll probably want to write your own chainable plugins/functions. It’s very easy to do this, since all you need to do is return the jQuery object at the end of the function.

In this example, we’ll write a plugin that attaches a second counter to an element.

Plugin

(function($) {
	$.fn.count = function() {
		return this.each(function() {  //We do an 'each', because the collection may have more than one item in it.
			var self = $(this);  //
			self.html('0');
			var theInterval = window.setInterval(function() {
				var c = parseFloat(self.text());
				self.html(c + 1);
			}, 1000);
		});
	}
}) (jQuery);

HTML

<div>
	<span id='test'></span>
</div>

Execution

$("#test").count().parent().addClass('counters'); //Chaining still works :)
Categories
PHP Programming

PHP Dark Arts: References

Remember the first time you dabbled in C?  Oh, the glorious typing, functions, and structs!  Now do you remember the first time you ran in to a pointer?  ‘*’, ‘&’, ‘->’ all made your hurt, but eventually you figured it out.  It’s fortunate (depending how you look at it) that we don’t have need to dabble with pointers or references while web programming these days.  However, PHP does allow us to passing things around by reference.  It’s not used often, but when used correctly can be very beneficial to the quality of your code.

What are PHP references?

The first thing you need to know about PHP references is that they are not C references.  You can’t do pointer arithmetic on them because they aren’t actually addresses.  In PHP references are actually symbol table aliases.  This means that you can have 2 variable names sharing the same variable content.

What can you do with references?

There are 3 things that you can do with PHP references.

  • Assign by reference.
  • Pass by reference.
  • Return by reference.
$x =& $y;
$x = 3;
echo "X: $x, Y: $y";

The above code sets $x and $y’s references to the same content area. Therefore, when $x is assigned 3, $y has access to the same data.

function add_item(&$item) {
   	$item++;
}
 
$totalItems = 0;
for($i = 0; $i <; 5; $i++) {
	add_item($totalItems);
}
echo "Total items: $totalItems";

This code allows you to modify a variable’s value without ever returning anything. In this example I made a simple counter, but you can set the value of $item to anything and it should work out just fine.

class Test {
	public $count = 0;
 
	public function &getCount() {
		return $this->count;
	}
}
 
$t = new Test();
$value = &$t->getCount();
$t->count = 25;
echo $value;

This code returns a reference to the public $count variable of the Test class. Generally this isn’t best practice, as it lowers the readability of the code.

Unsetting References

In the event that you want to free a variable from it’s reference to another, you can simply use the unset function.

$x =& $y;
unset($x);
Categories
Python

Fixing DreamHost’s Django Deployment Script

I recently created a trivial site locally with Django that I wanted to deploy on my DreamHost shared server.  DreamHost has made this process pretty painless by creating an easy-to-follow guide that can be found here.  The only problem is that it doesn’t work.  After entering in my project name and database info, i got the error message:

Creating project framework…  oops, django-admin failed to run!

With nothing to lose (and not wanting to figure out how to get Passenger set up on my own), I dove into their django-setup.py script.  As it turns out, the problem is on line 126.

if os.spawnl(os.P_WAIT, "/usr/bin/django-admin.py", "django-admin.py", "startproject", projname) != 0:

Apparently on DreamHost, django-admin.py has dropped the extension. So if you replace line 126 with the following, everything works great.

if os.spawnl(os.P_WAIT, "/usr/bin/django-admin", "django-admin", "startproject", projname) != 0: