<?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>The Daily Build &#187; django</title>
	<atom:link href="http://blog.bstpierre.org/category/django/feed" rel="self" type="application/rss+xml" />
	<link>http://blog.bstpierre.org</link>
	<description>Software Development, version 3.0</description>
	<lastBuildDate>Fri, 03 Feb 2012 02:59:01 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.4</generator>
		<item>
		<title>Five Days to a Django Web App: Day Four, Deployment</title>
		<link>http://blog.bstpierre.org/five-days-to-a-django-web-app-day-four-deployment</link>
		<comments>http://blog.bstpierre.org/five-days-to-a-django-web-app-day-four-deployment#comments</comments>
		<pubDate>Mon, 02 Mar 2009 16:48:20 +0000</pubDate>
		<dc:creator>Brian St. Pierre</dc:creator>
				<category><![CDATA[django]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.bstpierre.org/?p=169</guid>
		<description><![CDATA[Thanks for your patience, and for coming back for a discussion of deploying our Django web app. In case you missed any of the previous posts in this series, here they are: Day One, Get Ready (Concept and prep) Day Two, Mockups (Creating a design) Day Three, Coding (Coding tests, views, templates, and models) Pre-Deployment [...]]]></description>
			<content:encoded><![CDATA[<p>Thanks for your patience, and for coming back for a discussion of deploying our Django web app.</p>
<p>In case you missed any of the previous posts in this series, here they are:</p>
<ol>
<li><a href="/five-days-to-a-django-web-app-day-one-get-ready">Day One, Get Ready</a> (Concept and prep)</li>
<li><a href="/five-days-to-a-django-web-app-day-two-mockups">Day Two, Mockups</a> (Creating a design)</li>
<li><a href="/five-days-to-a-django-web-app-day-three-coding">Day Three, Coding</a> (Coding tests, views, templates, and models)</li>
</ol>
<h2>Pre-Deployment</h2>
<p>First, we need to make a couple of decisions:</p>
<ul>
<li>How are we going to push updates to the live site: FTP, git, svn?</li>
<li>How are we going to handle backups?</li>
</ul>
<h3>Version Control as Distribution System</h3>
<p>In my case, I&#8217;m using svn+ssh to push updates. Notice that this does not require special setup on your server &#8212; you do not need to install the svn stuff that DreamHost or your host may provide. Just do svn init to create a repository on the server (<em>outside</em> the DocumentRoot!). Then point your development pc to svn+ssh://USERNAME@host.example.com/home/USERNAME/svn/PROJECT. (Git works similarly, no support from your host required except the binaries.)</p>
<p>In the directory on the host where you&#8217;re going to store your project files, point to the same URL. (You could use the file:///&#8230;/ url, but I prefer to avoid accessing the repo directly. Superstition?)</p>
<p>Now, whenever you make a change on your development system, just &quot;svn ci&quot; and then on the host &#8220;svn up&#8221; and restart your fcgi to pick up the new code. Presto! The live site is updated with your change.</p>
<h3>Backups</h3>
<p>You must have a backup strategy: Your app will have users. Your host&#8217;s disk will burp. Your users will hate you when the disk burps and you don&#8217;t have a good backup.</p>
<p>There are probably 374 different ways of backing up your Django app. The two major things you need to capture are the database and your code. If you are storing objects (e.g. uploaded files) outside the database, you&#8217;ll need to back these up too. The option I&#8217;m using is <a href="http://code.google.com/p/django-backup/">django-backup</a>.</p>
<p>Pull the code from subversion into your project. Rename the directory to &quot;django_backup&quot;. Add django_backup to your INSTALLED_APPS. Verify it works by running <code>./manage.py backup -c</code>. Sanity check the backup by doing <code>zless backups/*.gz</code>. We&#8217;ll set up a cron job on the host to run this regularly when we deploy.</p>
<h2>Deploy</h2>
<p>I&#8217;ve previously written about <a href="/deploying-django-apps-on-dreamhost">deploying Django apps on DreamHost</a>, so I&#8217;m not going to duplicate that here. Keep in mind that you want to use the version control strategy outlined above. Read that article, deploy your app and come back here when you&#8217;re done.</p>
<h2>Post-Deployment</h2>
<h3>Backup</h3>
<p>Let&#8217;s add that cron job we previously mentioned. On the host, run <code>crontab -e</code>. If you&#8217;re on DreamHost and this if the first time you&#8217;ve used cron, it will prompt you for an email address to send output to. Then it will dump you into an editor. (Side note: &quot;joe&quot; is the default. If you want something different, like vim, be sure that EDITOR=/usr/bin/vim is set in your environment.)</p>
<p>Set up a job something similar to the following:</p>
<pre><code>
MAILTO="YOU@EXAMPLE.com"

# m h  dom mon dow   command
4 2 * * * (cd /home/PATH/TO/PROJECT; ./manage.py backup -c --email=YOU@EXAMPLE.com)
</code></pre>
<p>This will run a backup every day at 02:04 (AM). You will get two emails: one with the output from the job, and one with the compressed backup file. (When you get to the point where your database backups are too big for email, you&#8217;ll need to find another strategy.)</p>
<p>Now we&#8217;ve got another problem to solve: we&#8217;re going to accumulate a bunch of backups on the disk. Let&#8217;s get rid of the old backups. This is pretty safe, since we&#8217;re receiving backup files via email. Add a cron job like this:</p>
<pre><code>
14 2 * * * (cd /home/PATH/TO/PROJECT;
    touch --date=`date --iso --date='10 days ago'` .backup.oldest;
    find ./backups/ -mindepth 1 \! -newer .backup.oldest -execdir rm '{}' +)
</code></pre>
<p>(Formatted here for readability &mdash; you need to put that all on one line.)</p>
<p>This will remove backup files older than 10 days. You could do this more concisely with a tool like tmpwatch or tmpreaper, but neither is installed on my host and this incantation should work on pretty much any flavor and installation of linux.</p>
<p>At this point we&#8217;re deployed and the majority of the work is done. Tomorrow we&#8217;ll take a look at some maintenance issues.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.bstpierre.org/five-days-to-a-django-web-app-day-four-deployment/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Five Days to a Django Web App: Day Three, Coding</title>
		<link>http://blog.bstpierre.org/five-days-to-a-django-web-app-day-three-coding</link>
		<comments>http://blog.bstpierre.org/five-days-to-a-django-web-app-day-three-coding#comments</comments>
		<pubDate>Wed, 11 Feb 2009 15:14:41 +0000</pubDate>
		<dc:creator>Brian St. Pierre</dc:creator>
				<category><![CDATA[django]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[howto]]></category>

		<guid isPermaLink="false">http://blog.bstpierre.org/?p=141</guid>
		<description><![CDATA[Thanks for coming back for Day Three! [Note: Sorry this post is a day late. It was all ready to go late yesterday, but some of the code included below triggered a bug either in WordPress or ScribeFire and the whole post got mangled. I managed to resurrect it today from drafts, and I think [...]]]></description>
			<content:encoded><![CDATA[<p>Thanks for coming back for Day Three!</p>
<p>[Note: Sorry this post is a day late. It was all ready to go late yesterday, but some of the code included below triggered a bug either in WordPress or ScribeFire and the whole post got mangled. I managed to resurrect it today from drafts, and I think it's coherent, but if you find some problem with it please drop me a note.]</p>
<h2>Progress So Far</h2>
<p>Yesterday we <a href="../five-days-to-a-django-web-app-day-two-mockups">built some mockups</a>, just HTML and CSS — nothing active. Hopefully you’ve had a chance to run your mockups past a couple of people for feedback and ideas.</p>
<p>Armed with these mockups, we’re ready to get started coding. Today’s post is the longest in the series. Take it in chunks if you need to. (I didn’t write it all at once either.)</p>
<h2>Foundation</h2>
<h3>MySQL</h3>
<p>First, go to your web host’s control panel and create two MySQL databases for this project. I created &#8220;resumandb&#8221; and &#8220;test_resumandb&#8221;. This latter database is needed for running the built-in test system.</p>
<p>You’ll get an error/warning if the test database exists when you first run tests. However, the control panel needs to set user privileges and it seems like the only way it knows how to do this is by creating the database.</p>
<p>Set up the same databases on your local system:</p>
<pre><code>
bash$ mysql -u root
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1969
Server version: 5.0.32-Debian_7etch8-log Debian etch distribution

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql&gt; CREATE DATABASE resumandb;
Query OK, 1 row affected (0.00 sec)

mysql&gt; GRANT ALL ON resumandb.* TO 'resuman'@'localhost' identified
    by 'reallY_baD_9passworD!';
Query OK, 0 rows affected (0.11 sec)

mysql&gt; GRANT ALL ON test_resumandb.* TO 'resuman'@'localhost' identified
    by 'reallY_baD_9passworD!';
Query OK, 0 rows affected (0.0 sec)

</code></pre>
<p>Notice that you don&#8217;t need to create the test database. As mentioned above, this will happen when you run tests.</p>
<h3>Project Skeleton</h3>
<p>What follows is a bunch of steps: do-this, do-that. At the end of this section you should have a runnable (but empty) project that is ready to start hanging functionality onto.</p>
<p>Then generate a skeleton for your project: <code>django-admin.py  startproject YOURPROJECT</code>.</p>
<p>Then dive right in to settings.py and change a few things:</p>
<ul>
<li>Set the admin email to your email address.</li>
<li>Set the MySQL database according to your web host&#8217;s settings.</li>
<li>Timezone.</li>
<li>MEDIA_ROOT, MEDIA_URL and variants — see note below.</li>
<li>TEMPLATE_DIRS — see note below.</li>
</ul>
<p>To make it easier to use the same settings file to test both locally and on your host, I add the following to my settings.py to set MEDIA_ROOT and TEMPLATE_DIRS:</p>
<pre><code>
import os

def full_path_to(path):
    '''This makes this settings file relocatable.'''
    return os.path.join(os.getcwd(), path)

MEDIA_ROOT = full_path_to('static/')
TEMPLATE_DIRS = (
    full_path_to('templates')
)
</code></pre>
<p>Then you just have to make sure to cd to the directory where your settings.py lives whenever the app runs (more on this when we deploy to the host). I find this easier than monkeying with PYTHONPATH.</p>
<p>Similarly, the following will change your URLs based on whether you&#8217;re running locally or on the host. (Just make sure you test for a directory that only exists locally! My paths are a little different on the host.)</p>
<pre><code>
MEDIA_URL = 'http://media.resuman.com/resuman/static/'
if os.path.exists('/home/brian/projects/resuman'):
    MEDIA_URL = 'http://localhost/apache2-default/resuman-static/'

ADMIN_MEDIA_PREFIX = 'http://media.example.com/admin_media/'
if os.path.exists('/home/brian/projects/resuman'):
    ADMIN_MEDIA_PREFIX = 'http://localhost/apache2-default/resuman-admin/'
</code></pre>
<p>Now it&#8217;s time to generate the app: <code>./manage.py startapp YOURAPP</code>. Notice that the app name should be different from the project name (otherwise it gets too confusing later on).</p>
<p>Edit your YOURPROJECT/urls.py to include a reference to YOURAPP:</p>
<pre><code>
    (r'^funnel/$', include('resuman.jobfunnel.urls')),
</code></pre>
<p>Also uncomment the admin lines so you can use the built-in admin app.</p>
<p>Now it&#8217;s time to generate the app: <code>./manage.py startapp YOURAPP</code>.</p>
<p>Now edit YOURAPP/urls.py &#8212; paste in the needed bits from the existing urls.py, but drop the admin lines and the include().</p>
<p>In your settings file, add the admin and admindoc apps and &#8220;YOURPROJECT.YOURAPP&#8221; to INSTALLED_APPS.</p>
<p>Under the YOURPROJECT directory, create a templates directory and a static directory. Copy your HTML files from the mockup to the templates directory. Copy the CSS file to the static directory.</p>
<p>My system is configured by default to serve from /var/www/apache2-default/, and we specified above to fetch static files from http://localhost/resuman-static/, so we need to do the following to make this possible (substituting your paths, of course):</p>
<pre><code>
bash$ ln -s /home/brian/projects/resuman/static /var/www/apache2-default/resuman-static
bash$ ln -s /home/brian/projects/django/git/django/contrib/admin/media/ \
    /var/www/apache2-default/resuman-admin
</code></pre>
<p>Restart apache.</p>
<p>Change directory to YOURPROJECT and <code>./manage.py syncdb; ./manage.py runserver</code>.</p>
<p>Browse to <a href="http://127.0.0.1:8000/admin/">http://127.0.0.1:8000/admin/</a>. Log in, and you should see the admin app in all its glory. If the stylesheet didn&#8217;t load (ie. it looks really ugly), View Source on the page. At the top, find the URL to that ends something like &#8230;/resuman-admin/css/base.css. Copy-paste this into the address bar. It probably doesn&#8217;t load. Verify that it is the right URL — if not then change your settings.py to have the right URL base. If the URL is right, then you need to fix your symlink, server config, or permissions (I often get bit by having the wrong permissions).</p>
<h3>Adding Some Meat</h3>
<p>This wouldn&#8217;t be a bad time to push a snapshot into your version control system (e.g. <code>git init; git add .; git commit -m'YOURPROJECT skeleton done'</code>).</p>
<p>Now we&#8217;re finally ready to write the first view for this app. Edit YOURAPP/urls.py. Lay out the URL map that you want to use for your app. We&#8217;re on a tight five day schedule, so don&#8217;t go nuts! There&#8217;s only time to get a couple of pages done. Don&#8217;t worry, you can add more later. Here&#8217;s what mine looks like:</p>
<pre><code>
from django.conf.urls.defaults import *

urlpatterns = patterns(
    '',
    (r'^$', 'resuman.jobfunnel.views.dashboard'),
    (r'^add/$', 'resuman.jobfunnel.views.add_job'),
    (r'^edit/$', 'resuman.jobfunnel.views.edit_job'),
)
</code></pre>
<p>Remember that my toplevel urls.py includes this based on the <code>^funnel/$</code> pattern, so each of the patterns above will have …funnel/ as a prefix in the URL.</p>
<p>Now let’s write our first couple of tests. Edit YOURAPP/tests.py and add something similar to the code below. You’ll have to change URLs and logins. The class ViewTestCase is defined in viewtestcase.py, a convenience TestCase subclass I wrote for testing Django views. Copy that file into YOURAPPNAME directory.</p>
<pre><code>
from viewtestcase import ViewTestCase
class DashboardViewTestBase(ViewTestCase):
    # Override in subclass to use post/head/etc. Must match a
    # method defined in django.test.TestCase.
    TESTMETHOD = 'get'

    # Override.
    TESTURL = '/funnel/'
    TESTARGS = {}
    TEMPLATE = 'dashboard.html'

class DashboardViewLoginTest(DashboardViewTestBase):
    # We're expecting an error, so set TEMPLATE to None to avoid getting a bogus test failure.
    TEMPLATE = None

    def test_login_required(self):
        """
        Tests that a login is required to view the page.
        """
        self.expect_login_redirect()
        return

class DashboardViewTest(DashboardViewTestBase):
    # This uses TEMPLATE from the parent class.

    # Set username and password and the base class will automagically login the test client.
    USERNAME = 'brian'
    TESTLOGIN = (USERNAME, 'a')

    def test_logged_in_ok(self):
        pass
</code></pre>
<p>Now run the test: <code>./manage.py test</code>. You should see exactly two failures. If a bunch of stuff fails (like built-in django tests), fix whatever is wrong before continuing.</p>
<pre><code>
bash$ ./manage.py test
Creating test database...
Creating table django_admin_log
Creating table auth_permission
Creating table auth_group
Creating table auth_user
Creating table auth_message
Creating table django_content_type
Creating table django_session
Creating table django_site
Creating table jobfunnel_job
Installing index for admin.LogEntry model
Installing index for auth.Permission model
Installing index for auth.Message model
Installing index for jobfunnel.Job model
Installing json fixture 'initial_data' from '/home/brian/projects/resuman/../resuman/jobfunnel/fixtures'.
Installed 1 object(s) from 1 fixture(s)
..........EE......
======================================================================
ERROR: test_login_required (resuman.jobfunnel.tests.DashboardViewLoginTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/brian/projects/resuman/../resuman/jobfunnel/viewtestcase.py", line 98, in setUp
    self.fetch_view(self.TESTMETHOD, self.TESTURL, self.TESTARGS)
  File "/home/brian/projects/resuman/../resuman/jobfunnel/viewtestcase.py", line 79, in fetch_view
    self.response = function(testurl, testargs, **extra)
  File "/usr/lib/python2.5/site-packages/django/test/client.py", line 277, in get
    return self.request(**r)
  File "/usr/lib/python2.5/site-packages/django/core/handlers/base.py", line 77, in get_response
    request.path_info)
  File "/usr/lib/python2.5/site-packages/django/core/urlresolvers.py", line 183, in resolve
    sub_match = pattern.resolve(new_path)
  File "/usr/lib/python2.5/site-packages/django/core/urlresolvers.py", line 183, in resolve
    sub_match = pattern.resolve(new_path)
  File "/usr/lib/python2.5/site-packages/django/core/urlresolvers.py", line 124, in resolve
    return self.callback, args, kwargs
  File "/usr/lib/python2.5/site-packages/django/core/urlresolvers.py", line 136, in _get_callback
    raise ViewDoesNotExist, "Tried %s in module %s. Error was: %s" % (func_name, mod_name, str(e))
ViewDoesNotExist: Tried dashboard in module resuman.jobfunnel.views. Error was: 'module' object has no attribute 'dashboard'

======================================================================
ERROR: test_logged_in_ok (resuman.jobfunnel.tests.DashboardViewTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/brian/projects/resuman/../resuman/jobfunnel/viewtestcase.py", line 98, in setUp
    self.fetch_view(self.TESTMETHOD, self.TESTURL, self.TESTARGS)
  File "/home/brian/projects/resuman/../resuman/jobfunnel/viewtestcase.py", line 79, in fetch_view
    self.response = function(testurl, testargs, **extra)
  File "/usr/lib/python2.5/site-packages/django/test/client.py", line 277, in get
    return self.request(**r)
  File "/usr/lib/python2.5/site-packages/django/core/handlers/base.py", line 77, in get_response
    request.path_info)
  File "/usr/lib/python2.5/site-packages/django/core/urlresolvers.py", line 183, in resolve
    sub_match = pattern.resolve(new_path)
  File "/usr/lib/python2.5/site-packages/django/core/urlresolvers.py", line 183, in resolve
    sub_match = pattern.resolve(new_path)
  File "/usr/lib/python2.5/site-packages/django/core/urlresolvers.py", line 124, in resolve
    return self.callback, args, kwargs
  File "/usr/lib/python2.5/site-packages/django/core/urlresolvers.py", line 136, in _get_callback
    raise ViewDoesNotExist, "Tried %s in module %s. Error was: %s" % (func_name, mod_name, str(e))
ViewDoesNotExist: Tried dashboard in module resuman.jobfunnel.views. Error was: 'module' object has no attribute 'dashboard'

----------------------------------------------------------------------
Ran 18 tests in 4.364s

FAILED (errors=2)
Destroying test database...
</code></pre>
<p>Let’s write the view so the test will pass. Edit views.py:</p>
<pre><code>
@login_required
def dashboard(request):
    return render_to_response('dashboard.html',
                              {'title': 'Dashboard'},
                              context_instance=RequestContext(request))
</code></pre>
<p>This view uses a template called dashboard.html. Let’s make that template. Go back to the mockup for the dashboard. Copy everything into templates/base.html, then rip out the content so all you have left is the generic skeleton of a page in your app. Something like this (notice that this is using the title variable passed into the context by the view):</p>
<pre><code>
&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;

&lt;!--
# Resuman: keep track of job applications, cover letters, and resumes
#
# Copyright (c) 2009, Blakita Software LLC
# All rights reserved.
--&gt;

&lt;html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"&gt;
&lt;head&gt;
  &lt;meta http-equiv="Content-Type" content="text/html;charset=utf-8" /&gt;

  &lt;title&gt;
    {{ title }}
  &lt;/title&gt;

  &lt;style type="text/css"&gt;
    @import "{{ MEDIA_URL }}base.css";
  &lt;/style&gt;

  {% block scripts %}
  {% endblock scripts %}

&lt;/head&gt;

&lt;body&gt;

&lt;div id="container"&gt;

&lt;div id="menu"&gt;
TBD
&lt;/div&gt; &lt;!-- end div=menu --&gt;

&lt;div id="header"&gt;
&lt;h1&gt;{{ title }}&lt;/h1&gt;
&lt;/div&gt; &lt;!-- end div=header --&gt;

&lt;div id="content"&gt;

{% block content %}
{% endblock content %}

&lt;/div&gt; &lt;!-- end div=content --&gt;

&lt;div id="footer"&gt;
&lt;div class="nav"&gt;
  &lt;ul&gt;
    &lt;li&gt;&lt;a href="/"&gt;Home&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href="/blog/about"&gt;About&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href="/privacy.html"&gt;Privacy&lt;/a&gt;&lt;/li&gt;
  &lt;/ul&gt;
&lt;/div&gt;

&lt;div class="copyright"&gt;Copyright © 2009, Blakita Software LLC&lt;/div&gt;
&lt;/div&gt; &lt;!-- end div=footer --&gt;

&lt;/div&gt; &lt;!-- end div=container --&gt;

&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>Now take the content you ripped out and put it into dashboard.html:</p>
<pre><code>
{% extends "base.html" %}

{% block content %}
&lt;ul id="funnel"&gt;
  &lt;li class="phase first"&gt;
    &lt;div class="phase"&gt;Applied&lt;/div&gt;
    &lt;div class="companies"&gt;
    &lt;ul class="companies"&gt;
        &lt;li class="company"&gt;AAA&lt;/li&gt;
    &lt;/ul&gt;
    &lt;/div&gt;
  &lt;/li&gt;
  &lt;li class="phase"&gt;
    &lt;div class="phase"&gt;Confirmed&lt;/div&gt;
    &lt;div class="companies"&gt;
    &lt;ul class="companies"&gt;
        &lt;li class="company"&gt;BBB&lt;/li&gt;
        &lt;li class="company"&gt;CCC&lt;/li&gt;
    &lt;/ul&gt;
    &lt;/div&gt;
  &lt;/li&gt;
  &lt;li class="phase"&gt;
    &lt;div class="phase"&gt;Screen&lt;/div&gt;
    &lt;div class="companies"&gt;
    &lt;ul class="companies"&gt;
        &lt;li class="company"&gt;Fubar&lt;/li&gt;
    &lt;/ul&gt;
    &lt;/div&gt;
  &lt;/li&gt;
  &lt;li class="phase"&gt;
    &lt;div class="phase"&gt;Interview&lt;/div&gt;
    &lt;div class="companies"&gt;
    &lt;ul class="companies"&gt;
        &lt;li class="company"&gt;Rabuf&lt;/li&gt;
    &lt;/ul&gt;
    &lt;/div&gt;
  &lt;/li&gt;
  &lt;li class="phase"&gt;
    &lt;div class="phase"&gt;Offer&lt;/div&gt;
    &lt;div class="companies"&gt;
    &lt;ul class="companies"&gt;
        &lt;li class="company"&gt;Oof Rab&lt;/li&gt;
    &lt;/ul&gt;
    &lt;/div&gt;
  &lt;/li&gt;
  &lt;li class="phase last"&gt;
    &lt;div class="phase"&gt;Start!&lt;/div&gt;
    &lt;div class="companies"&gt;
    &lt;ul class="companies"&gt;
        &lt;li class="company"&gt;Rab Oof&lt;/li&gt;
    &lt;/ul&gt;
    &lt;/div&gt;
  &lt;/li&gt;
&lt;/ul&gt;

{% endblock content %}
</code></pre>
<p>Obviously this still just has dummy static data. We&#8217;ll get some active data in there very soon, but now we&#8217;re ready to rerun the test. It should pass this time. If not, fix the problem. When you get all tests passing, celebrate!</p>
<p>For real data, we need to write the model(s) used by this app. Let&#8217;s add another test:</p>
<pre><code>
class DashboardViewTest(DashboardViewTestBase):
    USERNAME = 'brian'
    TESTLOGIN = (USERNAME, 'a')

    def test_company_list(self):
        self.expect_div_content('content', 'Foobar Corp')
        return
</code></pre>
<p>Edit models.py to add the model:</p>
<pre><code>
from django.contrib.auth.models import User
from django.db import models

class Job(models.Model):
    applicant = models.ForeignKey(User)
    company = models.CharField(max_length=80)
</code></pre>
<p>The test depends on having a job in the database. Let&#8217;s set up a test fixture. Edit YOURAPPNAME/fixtures/initial_data.json:</p>
<pre><code>
[{"pk": 1, "model": "auth.user", "fields":
    {"username": "brian", "first_name": "", "last_name": "",
     "is_active": 1, "is_superuser": 0, "is_staff": 0,
     "last_login": "2009-02-06 13:50:02", "groups": [], "user_permissions": [],
     "password": "sha1$0fcc8$c4cf5184f5c005f90165e782fb090e7d75b72986",
     "email": "brian@example.com", "date_joined": "2009-02-06 13:44:04"}},
 {"pk": 2, "model": "auth.user", "fields":
    {"username": "alan", "first_name": "", "last_name": "",
     "is_active": 1, "is_superuser": 0, "is_staff": 0,
     "last_login": "2009-02-06 13:50:02", "groups": [], "user_permissions": [],
     "password": "sha1$0fcc8$c4cf5184f5c005f90165e782fb090e7d75b72986",
     "email": "alan@example.org", "date_joined": "2009-02-06 13:44:04"}},
 {"pk": 1, "model": "jobfunnel.job", "fields":
    {"position_url": "http://example.com/career/", "title": "Foobar Eng",
     "company_url": "http://example.com/", "company": "Foobar Corp", "applicant": 1,
     "phase": "Apply", "date": "2009-02-11", "position": "Engineer",
     "notes": "Applied via website"}}
]
</code></pre>
<p>This will populate the database with a couple of users, both with password &#8220;a&#8221;, and a job before each test runs.</p>
<p>Run this test, expecting exactly one failure — the content div does not contain the expected string. Let&#8217;s grab the list of jobs in the view and pass it into the template:</p>
<pre><code>
@login_required
def dashboard(request):
    jobs = models.Job.objects.all()
    return render_to_response('dashboard.html',
                              {'title': 'Dashboard',
                               'jobs': jobs,
                               },
                              context_instance=RequestContext(request))
</code></pre>
<p>I won&#8217;t paste all of the code here again, but we need to edit the template to use the jobs list:</p>
<pre><code>
    &lt;ul class="companies"&gt;
      {% for job in jobs %}
        &lt;li class="company"&gt;{{ job.company }}&lt;/li&gt;
      {% empty %}
        &lt;li class="company"&gt;No jobs in this phase.&lt;/li&gt;
      {% endfor %}
    &lt;/ul&gt;
</code></pre>
<p>Now rerun the test and expect it to pass. Hooray!</p>
<p>One last refinement before we quit for today: users shouldn&#8217;t be able to see each others applications. The way this is coded, all jobs are going to show up on everybody&#8217;s dashboards. Not good. Here&#8217;s another test that checks that the application for Foobar Corp only shows up on Brian&#8217;s dashboard, not on Alan&#8217;s.</p>
<pre><code>
class PrivateDashboardViewTest(DashboardViewTestBase):
    USERNAME = 'alan'
    TESTLOGIN = (USERNAME, 'a')

    def test_private_applications(self):
        assert('Foobar' not in self.get_div_content('content'))
        return
</code></pre>
<p>Run the test, watch it fail, and then change one line in the view:</p>
<pre><code>
    jobs = models.Job.objects.filter(applicant=request.user)
</code></pre>
<p>Now the all the tests should pass.</p>
<p>Push a copy of your code into your version control tool. Take a break, you deserve it.</p>
<p>For &#8220;homework&#8221;, put together your other views in the same way as this one. We’ll look at deployment tomorrow.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.bstpierre.org/five-days-to-a-django-web-app-day-three-coding/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Five Days to a Django Web App: Day Two, Mockups</title>
		<link>http://blog.bstpierre.org/five-days-to-a-django-web-app-day-two-mockups</link>
		<comments>http://blog.bstpierre.org/five-days-to-a-django-web-app-day-two-mockups#comments</comments>
		<pubDate>Tue, 10 Feb 2009 14:40:54 +0000</pubDate>
		<dc:creator>Brian St. Pierre</dc:creator>
				<category><![CDATA[django]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://blog.bstpierre.org/?p=139</guid>
		<description><![CDATA[Welcome back. Ready for Day Two? Did you get your &#8220;hello world&#8221; app running on your host? Where We Stand Yesterday we nailed down our concept, bought a domain name and hosting, set up our toolkit, and deployed a practice app on the host. Here&#8217;s what I&#8217;m going to build: a web app to keep [...]]]></description>
			<content:encoded><![CDATA[<p>Welcome back.</p>
<p>Ready for Day Two? Did you get your &#8220;hello world&#8221; app running on your host?</p>
<h3>Where We Stand</h3>
<p><a href="http://blog.bstpierre.org/five-days-to-a-django-web-app-day-one-get-ready">Yesterday</a> we nailed down our concept, bought a domain name and hosting, set up our toolkit, and deployed a practice app on the host.</p>
<p>Here&#8217;s what I&#8217;m going to build: a web app to keep track of job applications, cover letters, and resumes. The working name for the project is &#8220;resuman&#8221;. Unfortunately, that obvious domain name was already registered and I&#8217;m not up for buying from the current owner. So after trying a bunch of more-or-less obvious combinations, I grabbed &#8220;yresu.me&#8221;, and I&#8217;ll deploy the app at &#8220;trackm.yresu.me&#8221;.</p>
<h3>Notes on Domain Registration</h3>
<p>It&#8217;s worth making a couple of notes here on the domain registration process. I use <a href="http://godaddy.com">GoDaddy</a> for my registrations. In the past I&#8217;ve done registration with my preferred host, but if you end up switching hosts it&#8217;s a hassle to move the domain registrations. Another complication: hosting services like DreamHost only support registrations on the major TLDs (.com, .org, .net, .info), while a full-service registrar like GoDaddy supports alternatives like .me.</p>
<p>Lastly, I like the bulk domain search service from <a href="http://dotster.com/">Dotster</a>. You can search for up to 50 names at a time. So if your first choice is unavailable, use Dotster&#8217;s bulk search tool to enter a whole mess of variations and see what&#8217;s available. This is the process I used to find yresu.me — the search included resu.me, esu.me, su.me, and myresu.me, all of which were taken.</p>
<h3>Make Some Mockups</h3>
<p>Before we commit any design ideas to HTML, let&#8217;s take some great advice from 37signals: <a href="http://gettingreal.37signals.com/ch06_From_Idea_to_Implementation.php">sketch a bunch of drafts on paper first</a>. To back up this idea, check out this story posted by Jeff Atwood about <a href="http://www.codinghorror.com/blog/archives/001160.html">quantity vs. quality</a>:</p>
<blockquote><p>The ceramics teacher announced on opening day that he was dividing the class into two groups. All those on the left side of the studio, he said, would be graded solely on the quantity of work they produced, all those on the right solely on its quality. His procedure was simple: on the final day of class he would bring in his bathroom scales and weigh the work of the &#8220;quantity&#8221; group: fifty pound of pots rated an &#8220;A&#8221;, forty pounds a &#8220;B&#8221;, and so on. Those being graded on &#8220;quality&#8221;, however, needed to produce only one pot &#8211; albeit a perfect one &#8211; to get an &#8220;A&#8221;.</p>
<p>Well, came grading time and a curious fact emerged: the works of highest quality were all produced by the group being graded for quantity. It seems that while the &#8220;quantity&#8221; group was busily churning out piles of work &#8211; and learning from their mistakes &#8211; the &#8220;quality&#8221; group had sat theorizing about perfection, and in the end had little more to show for their efforts than grandiose theories and a pile of dead clay.</p></blockquote>
<p>So my advice to you is to produce no fewer than five different designs on paper. It only takes a few minutes to sketch something out and see what it looks like. I did a handful of drawings on paper with my kids&#8217; crayons, and then some refinements on my whiteboard once I had chosen the general design. So use whatever media you have handy, and don&#8217;t worry about getting it perfect. Run your sketches by a couple of innocent bystanders for some feedback.</p>
<p><img class="size-medium wp-image-147" title="Mockups on my whiteboard." src="http://blog.bstpierre.org/wp-content/uploads/2009/02/whiteboard-mockup-300x203.jpg" alt="Mockups on my whiteboard." width="300" height="203" /></p>
<p>Once you&#8217;ve got a good design on paper, make mockups in HTML and CSS. Steve Dennis at subcide.com has a great walkthrough on <a href="http://www.subcide.com/tutorials/csslayout/">creating a CSS layout from scratch</a>. If you don&#8217;t have an established process for building up a design, follow his tutorial. Putting together the HTML+CSS takes a little more time than sketches on paper, but it&#8217;s still worth doing a couple of different designs to see what grabs you. I worked up two different CSS layouts on top of the same HTML. Run these designs by some people — now that you&#8217;ve got some code, you can upload it to your site and email a link to some friends. Pick the better of the two (or three).</p>
<p>Better yet, upload the mockups to your host and leave a comment here with a link to them. Traffic here is low enough that I should be able to reply with feedback. (Although feel free to circulate a link to this series to a hundred of your friends, or post it to digg. I&#8217;ll at least reply to the first 50 comments&#8230;)</p>
<p>Tomorrow we&#8217;ll start writing some code.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.bstpierre.org/five-days-to-a-django-web-app-day-two-mockups/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Five Days to a Django Web App: Day One, Get Ready</title>
		<link>http://blog.bstpierre.org/five-days-to-a-django-web-app-day-one-get-ready</link>
		<comments>http://blog.bstpierre.org/five-days-to-a-django-web-app-day-one-get-ready#comments</comments>
		<pubDate>Mon, 09 Feb 2009 15:15:09 +0000</pubDate>
		<dc:creator>Brian St. Pierre</dc:creator>
				<category><![CDATA[django]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://blog.bstpierre.org/?p=135</guid>
		<description><![CDATA[This is the first in a series of posts that will walk through the steps of designing, building, and deploying a complete web app using Django. I&#8217;m going to assume you know the basics when it comes to Python, Django, HTML, CSS, Javascript and some basic tools. This will be a part time effort, so [...]]]></description>
			<content:encoded><![CDATA[<p>This is the first in a series of posts that will walk through the steps of designing, building, and deploying a complete web app using Django. I&#8217;m going to assume you know the basics when it comes to Python, Django, HTML, CSS, Javascript and some basic tools. This will be a part time effort, so you should be able to work alongside me in a couple of hours a day.</p>
<p>A word about costs: you&#8217;ll need to spend ten bucks or so for a domain name, and anywhere from $30 to $150+ for hosting if you don&#8217;t already have these set up. Of course, you can just follow along on your server at home for free, but you&#8217;ll learn more if it&#8217;s all live when everything is said and done.</p>
<p>Let&#8217;s get started.</p>
<h2>Day 1: Get Ready</h2>
<h3>Concept</h3>
<p>We need to figure out what we&#8217;ll be building, and we need to get a few things set up.</p>
<p>First, you need an idea. It doesn&#8217;t have to be the next <a href="http://twitter.com/">Twitter</a>. Try to pick something simple that you&#8217;ll be able to code up in a couple of evenings, but useful enough that it&#8217;s worth doing right.</p>
<p>Let that simmer on the back burner, and let&#8217;s get some stuff set up.</p>
<h3>Hosting</h3>
<p>You will need someplace to host the app. As noted above, you can do this on your own machine at home, but it&#8217;s good practice to set it up live — the learning will be stickier too.</p>
<p><a href="http://www.webfaction.com/">Webfaction</a> is highly recommended for Django hosting, but it can be a bit pricey if you&#8217;re just experimenting.</p>
<p>Deploying Django on <a href="http://dreamhost.com/">Dreamhost</a> will suffer a bit performance-wise, but if you <a href="http://www.google.com/search?q=dreamhost+coupon">google for a coupon</a> you may be able to get up to $97 off. So for $30 you can get a year&#8217;s worth of hosting. Not bad.</p>
<p>Go off and do this. Now. This post will still be here when you come back.</p>
<h3>Domain</h3>
<p>Obviously, you&#8217;re going to need a domain name where your app will live.</p>
<p>How&#8217;s that idea you&#8217;ve been simmering for the past 20 minutes? Good, now pick a domain name to go with it. You can let this simmer for a while too, but remember that the name can take a day or two to propagate through DNS once you&#8217;ve purchased it.</p>
<p>Not sure about Webfaction, but you can buy this through Dreamhost for $10 or $15. Depending on what kinds of promotions they&#8217;re offering, you may even have a credit for a free domain name when you signed up for hosting.</p>
<p>Go ahead and snag that domain now, I&#8217;ll wait patiently&#8230;</p>
<h3>Tools</h3>
<p>Since you don&#8217;t want to develop on the hosting platform, you&#8217;ll need to install some things on your own machine so you can develop and test. This is the minimum I&#8217;ve been using, please leave a comment if there&#8217;s something you think I&#8217;m missing.</p>
<ul>
<li>Apache with mod_python (used at Webfaction) or mod_fastcgi (used at Dreamhost). If you have a different host (or you&#8217;re reading this at some future date and the options have changed), just make sure that what you&#8217;re using matches them.</li>
<li>Editor</li>
<li>Firefox with the <a href="http://www.getfirebug.com/">Firebug</a> and <a href="http://chrispederick.com/work/web-developer/">Web Developer</a> add-ons.</li>
<li>Python</li>
<li>Django. I use the trunk. (Actually, I pull from <a href="http://github.com/bstpierre/django/">my github fork</a>.)</li>
<li><a href="http://seleniumhq.org/">Selenium</a></li>
</ul>
<p>It will be helpful if you can install the tools in the same way — including the same paths — that you have on your web host. If this isn&#8217;t practical, it isn&#8217;t a big deal, but it will make your life easier down the road when you&#8217;re trying to figure out why something works locally but doesn&#8217;t work on the live site.</p>
<p>That&#8217;s it for today. As homework, <a href="http://blog.bstpierre.org/deploying-django-apps-on-dreamhost">set up a practice &#8220;hello world&#8221; app on your host</a> so that you know everything is working.</p>
<p><strong>Update</strong>: continue this series with <a href="http://blog.bstpierre.org/five-days-to-a-django-web-app-day-two-mockups">day two: mockups</a>.</p>
<p><a href="http://blog.bstpierre.org/feed/rss2">Subscribe to The Daily Build</a> to make sure you get all the posts in this series!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.bstpierre.org/five-days-to-a-django-web-app-day-one-get-ready/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Deploying Django Apps on Dreamhost</title>
		<link>http://blog.bstpierre.org/deploying-django-apps-on-dreamhost</link>
		<comments>http://blog.bstpierre.org/deploying-django-apps-on-dreamhost#comments</comments>
		<pubDate>Tue, 03 Feb 2009 15:42:04 +0000</pubDate>
		<dc:creator>Brian St. Pierre</dc:creator>
				<category><![CDATA[django]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://blog.bstpierre.org/deploying-django-apps-on-dreamhost</guid>
		<description><![CDATA[The Dreamhost wiki article on Django helped, but all the steps starting from scratch aren&#8217;t really documented in one place. Hopefully the list below will help, but since I&#8217;m writing it after the fact and I had to go through a couple of iterations to get it right, there are probably some things that aren&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://wiki.dreamhost.com/Django">Dreamhost wiki article on Django</a> helped, but all the steps starting from scratch aren&#8217;t really documented in one place. Hopefully the list below will help, but since I&#8217;m writing it after the fact and I had to go through a couple of iterations to get it right, there are probably some things that aren&#8217;t 100% right.</p>
<ol>
<li><a href="http://wiki.dreamhost.com/Python">Read the python article.</a> Set up virtualenv into $HOME/local.</li>
<li>If you&#8217;ve already messed around with installing MySQLdb and/or other packages, remove them and start over.</li>
<li>Install ez_setup (easy_install) as describe in the article.</li>
<li>Install the MySQL egg: easy_install MySQL_python</li>
<li>Follow the setup steps in the <a href="http://wiki.dreamhost.com/Django">Django article</a>. Do the &#8220;myproject&#8221; test using sqlite3. Really. It helped me find a couple of things I was doing wrong with my real (i.e. more complicated) MySQL project.</li>
<li>As a deviation from the Django setup instructions, I prefer to use a fork of the Django codebase with some of my own patches. If you&#8217;re in the same situation, use <a href="http://github.com/bstpierre/">github</a>. I forked the github &#8220;unofficial copy&#8221; of the subversion code, added a couple of patches that aren&#8217;t in the trunk yet and a couple of my own, and cloned a copy into my dreamhost account.</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://blog.bstpierre.org/deploying-django-apps-on-dreamhost/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

