<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
     xmlns:content="http://purl.org/rss/1.0/modules/content/"
     xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
     xmlns:atom="http://www.w3.org/2005/Atom"
     xmlns:dc="http://purl.org/dc/elements/1.1/"
     xmlns:wfw="http://wellformedweb.org/CommentAPI/"
     >
  <channel>
    <title>Dougal Matthews Home</title>
    <link>None</link>
    <description>Personal site and portfolio for Dougal Matthews</description>
    <pubDate>Thu, 29 Dec 2011 14:46:13 GMT</pubDate>
    <generator>Blogofile</generator>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>New Year's Python Meme</title>
      <link>http://www.dougalmatthews.com/2011/12/23/new-year's-python-meme</link>
      <pubDate>Fri, 23 Dec 2011 14:21:00 GMT</pubDate>
      <category><![CDATA[python]]></category>
      <guid>k3t_WVd-3qTiqNEWq7cvVCpClKE=</guid>
      <description>New Year's Python Meme</description>
      <content:encoded><![CDATA[<p><strong>What is the coolest Python application, framework, or library you
have discovered in 2011?</strong></p>
<p>I started using Tox in all my projects this year. It's got to be one of the
best addition for testing multiple platforms and package versions.</p>
<p><strong>What new programming technique did you learn in 2011?</strong></p>
<p>I love testing, and have been good at writing tests for my code, but I've been
naturally moving towards a stricter TDD testing style, and I've been some
great benifits from this.</p>
<p><strong>What’s the name of the open source project you contributed the
most in 2011? What did you do?</strong></p>
<p>I contributed mostly to a number of my own new (or newly released) projects;
<a href="https://github.com/d0ugal/html5video">html5video</a>,
<a href="https://github.com/d0ugal/znc_mailer">znc_mailer</a>,
<a href="https://github.com/d0ugal/django-appregister">django-appregister</a>,
<a href="https://github.com/d0ugal/django-urlmiddleware">django-urlmiddleware</a>,
<a href="https://github.com/d0ugal/django-consent">django-consent</a>,
<a href="https://github.com/d0ugal/django-gauge">django-gauge</a>.</p>
<p><strong>What was the Python blog or website you read the most in 2011?</strong></p>
<p>Planet Python and Python Redit. I've also started reading Hackernews more,
which fairly often has Python related content.</p>
<p><strong>What are the three top things you want to learn in 2012?</strong></p>
<p>Pyramid, More of Python's internals, Haskell. The last has been on my list
for a while.</p>
<p><strong>What are the top software, app, or lib you wish someone would
write in 2012?</strong></p>
<p>I'd like somebody to build a CI server that uses ep.io to deploy testing apps
and run the tests and then deploy to the production app.</p>
<p><strong>Want to do your own list ? here’s how:</strong></p>
<ul>
<li>copy-paste the questions and answer to them in your blog</li>
<li>tweet it with the #2012pythonmeme hashtag</li>
</ul>]]></content:encoded>
    </item>
    <item>
      <title>Making Django's signals asynchronous with Celery</title>
      <link>http://www.dougalmatthews.com/2011/10/10/making-django's-signals-asynchronous-with-celery</link>
      <pubDate>Mon, 10 Oct 2011 17:21:00 BST</pubDate>
      <category><![CDATA[python]]></category>
      <category><![CDATA[django]]></category>
      <guid>T0z-rfTNEP_xo88PA7rp3RZuxHc=</guid>
      <description>Making Django's signals asynchronous with Celery</description>
      <content:encoded><![CDATA[<p><strong>Update:</strong> A comment on <a href="https://code.djangoproject.com/ticket/17029">the ticket</a>
I opened by Alex Gaynor brought up a point that I hadn't fully considered. It's
worth noticing before going further in this post and also worth pointing out my
monkey patch doesn't answer this question.</p>
<blockquote>
<p>After speaking with Carl, I'm marking this as wontfix because it is
non-obvious as to whether pickling a Signal should include the registered
receivers, and how that interacts with the weak referencing, since there's no
obvious semantic it seems better not to guess.</p>
</blockquote>
<p>I really enjoy working with both Django's signal framework and Celery tasks.
Today it occured to me that it would be useful to combine the two and have
“asynchronous signals”.</p>
<p>Here is the solution that I came up with, read on below if you want to see how
I arrived at this and why we need to monkey patch.</p>
<div class="codehilite"><pre><span class="kn">from</span> <span class="nn">celery.task</span> <span class="kn">import</span> <span class="n">task</span>
<span class="kn">from</span> <span class="nn">django.db.models.signals</span> <span class="kn">import</span> <span class="n">post_save</span>

<span class="kn">from</span> <span class="nn">myproject.models</span> <span class="kn">import</span> <span class="n">MyModel</span>

<span class="c"># Warning. Monkey patch.</span>
<span class="kn">from</span> <span class="nn">django.dispatch.dispatcher</span> <span class="kn">import</span> <span class="n">Signal</span>
<span class="k">def</span> <span class="nf">reducer</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
    <span class="k">return</span> <span class="p">(</span><span class="n">Signal</span><span class="p">,</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">providing_args</span><span class="p">,))</span>
<span class="n">Signal</span><span class="o">.</span><span class="n">__reduce__</span> <span class="o">=</span> <span class="n">reducer</span>

<span class="c"># With the patch done, we can now connect to celery tasks.</span>
<span class="nd">@task</span><span class="p">(</span><span class="n">ignore_result</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">async_post_save</span><span class="p">(</span><span class="n">sender</span><span class="p">,</span> <span class="n">instance</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
    <span class="c"># do something with the instance.</span>
    <span class="k">pass</span>
<span class="n">post_save</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">async_post_save</span><span class="o">.</span><span class="n">delay</span><span class="p">,</span> <span class="n">sender</span><span class="o">=</span><span class="n">MyModel</span><span class="p">)</span>
</pre></div>


<p>The first solution that occured to me was to use an intermediate function that
triggered the task. This works fine and doesn't require anything clever.</p>
<div class="codehilite"><pre><span class="kn">from</span> <span class="nn">celery.task</span> <span class="kn">import</span> <span class="n">task</span>
<span class="kn">from</span> <span class="nn">django.db.models.signals</span> <span class="kn">import</span> <span class="n">post_save</span>

<span class="kn">from</span> <span class="nn">myproject.models</span> <span class="kn">import</span> <span class="n">MyModel</span>

<span class="nd">@task</span>
<span class="k">def</span> <span class="nf">async_post_save</span><span class="p">(</span><span class="n">instance</span><span class="p">):</span>
    <span class="c"># do something with the instance.</span>
    <span class="k">pass</span>

<span class="k">def</span> <span class="nf">post_save_reciever</span><span class="p">(</span><span class="n">sender</span><span class="p">,</span> <span class="n">instance</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
    <span class="n">async_post_save</span><span class="o">.</span><span class="n">delay</span><span class="p">()</span>
<span class="n">post_save</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">post_save_reciever</span><span class="p">)</span>
</pre></div>


<p>However, this adds an extra level of redirection to code that shouldn't be
needed. Why can't be connect to tasks directly?</p>
<div class="codehilite"><pre><span class="nd">@task</span><span class="p">(</span><span class="n">ignore_result</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">async_post_save</span><span class="p">(</span><span class="n">sender</span><span class="p">,</span> <span class="n">instance</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
    <span class="c"># do something with the instance.</span>
    <span class="k">pass</span>
<span class="n">post_save</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">async_post_save</span><span class="o">.</span><span class="n">delay</span><span class="p">,</span> <span class="n">sender</span><span class="o">=</span><span class="n">MyModel</span><span class="p">)</span>
</pre></div>


<p>This almost works, however, in the kwargs signal recievers are passed an
instance of django.display.dispatcher.Signal and this contains an instance
of threading.Lock - an object that can't be pickled. This leads me to the
monkey patch that was shown at the start of this article which simply adds
a <strong>reduce</strong> method to the Signal class that alters the pickle behaviour and
only pickles the provided_args property of the Signal instance.</p>
<p>Incidently, you'll notice that I added ignore_result=True to each of the tasks.
While this isn't required, its not generally standard practice for signals
recievers to return anything, so you will probably want to do this too.</p>
<p><a href="https://code.djangoproject.com/ticket/17029">View the ticket I opened a ticket to track this idea This link</a></p>]]></content:encoded>
    </item>
    <item>
      <title>My Vagrant Workflow</title>
      <link>http://www.dougalmatthews.com/2011/02/27/my-vagrant-workflow</link>
      <pubDate>Sun, 27 Feb 2011 19:25:00 GMT</pubDate>
      <category><![CDATA[python]]></category>
      <category><![CDATA[vagrant]]></category>
      <guid>6BaUNm0lclP4O689nikiVSLeofA=</guid>
      <description>My Vagrant Workflow</description>
      <content:encoded><![CDATA[<p><a href="http://vagrantup.com/">Vagrant</a> is a command line tool for managing virtual 
machines aimed at virtualising your development environment. It is 
essentially a wrapper around Oracle's <a href="http://www.virtualbox.org/">VirtualBox</a> 
but a very good one. </p>
<p>Getting started is really easy, there is a good quick start on the Vagrant
website, or you can try my version to get a development environment I've been
using - which is a basic box with some Python tools and postgres. Vagrant 
projects are initialised for a directory and simply contains a file called 
Vagrantfile (and an automatically generated .vagrant file). Generally speaking 
I would then do this once in each project root allowing the vagrant file to 
be version controlled and configured for an individual project. Then each 
developer can create a virtual machine from the same config and this keeps 
everybody on the same page.</p>
<div class="codehilite"><pre>sudo gem update --system
gem install vagrant
<span class="nb">cd</span> /path/to/project
vagrant init
</pre></div>


<p>You may not need the first step there, but I did on my mac. There is a 
detailed setup guide for different platforms 
<a href="http://vagrantup.com/docs/getting-started/index.html">here</a>. So if you have
any problems make sure you read that first.</p>
<p>In your current directory you should now have a file named <code>Vagrantfile</code>. This
is a simple Ruby based configuration file. The Vagrantfile is 
<a href="http://vagrantup.com/docs/vagrantfile.html">well documented</a> so we'll skip
past that bit. Instead, copy the following into your vagrant file.</p>
<div class="codehilite"><pre><span class="no">Vagrant</span><span class="o">::</span><span class="no">Config</span><span class="o">.</span><span class="n">run</span> <span class="k">do</span> <span class="o">|</span><span class="n">config</span><span class="o">|</span>

  <span class="n">config</span><span class="o">.</span><span class="n">vm</span><span class="o">.</span><span class="n">box</span> <span class="o">=</span> <span class="s2">&quot;lucid32&quot;</span>
  <span class="n">config</span><span class="o">.</span><span class="n">vm</span><span class="o">.</span><span class="n">box_url</span> <span class="o">=</span> <span class="s2">&quot;http://files.vagrantup.com/lucid32.box&quot;</span>

  <span class="n">config</span><span class="o">.</span><span class="n">vm</span><span class="o">.</span><span class="n">forward_port</span><span class="p">(</span><span class="s2">&quot;web&quot;</span><span class="p">,</span> <span class="mi">8000</span><span class="p">,</span> <span class="mi">8000</span><span class="p">)</span>
  <span class="n">config</span><span class="o">.</span><span class="n">vm</span><span class="o">.</span><span class="n">network</span><span class="p">(</span><span class="s2">&quot;33.33.00.10&quot;</span><span class="p">)</span>

  <span class="n">config</span><span class="o">.</span><span class="n">vm</span><span class="o">.</span><span class="n">provision</span> <span class="ss">:chef_solo</span> <span class="k">do</span> <span class="o">|</span><span class="n">chef</span><span class="o">|</span>

    <span class="n">chef</span><span class="o">.</span><span class="n">recipe_url</span> <span class="o">=</span> <span class="s2">&quot;http://cloud.github.com/downloads/d0ugal/chef_recipes/cookbooks.tar.gz&quot;</span>
    <span class="n">chef</span><span class="o">.</span><span class="n">cookbooks_path</span> <span class="o">=</span> <span class="o">[</span><span class="ss">:vm</span><span class="p">,</span> <span class="s2">&quot;cookbooks&quot;</span><span class="o">]</span>

    <span class="n">chef</span><span class="o">.</span><span class="n">add_recipe</span> <span class="s2">&quot;main&quot;</span>
    <span class="n">chef</span><span class="o">.</span><span class="n">add_recipe</span> <span class="s2">&quot;python&quot;</span>
    <span class="n">chef</span><span class="o">.</span><span class="n">add_recipe</span> <span class="s2">&quot;postgres&quot;</span>

    <span class="n">chef</span><span class="o">.</span><span class="n">json</span><span class="o">.</span><span class="n">merge!</span><span class="p">({</span>

      <span class="ss">:project_name</span> <span class="o">=&gt;</span> <span class="s2">&quot;project_name&quot;</span><span class="p">,</span>

      <span class="ss">:system_packages</span> <span class="o">=&gt;</span> <span class="o">[]</span><span class="p">,</span>
      <span class="ss">:python_global_packages</span> <span class="o">=&gt;</span> <span class="o">[]</span><span class="p">,</span>
      <span class="ss">:python_packages</span> <span class="o">=&gt;</span> <span class="o">[]</span><span class="p">,</span>

    <span class="p">})</span>

  <span class="k">end</span>

<span class="k">end</span>
</pre></div>


<p>After copying in, look for project_name and change that to something on your
liking or you can just leave it for now.</p>
<blockquote>
<p>If you have already been using vagrant, you will likely have the lucid box
already. The vagrant quick start tips download it and call it 'base' since
this is a common name I have changed it to something more explicit and
safe. However, to avoid re-downloading you may want to change lucid32 to
base in your config file.</p>
</blockquote>
<p>What does this do? It setups up a new Ubuntu Lucid machine and runs some 
chef recipies against that are downloading from my chef github repository. 
The base machine that its built on is downloaded from the url in the config 
this is provided by the Vagrant team (I've not had a chance to make my own
boxes yet).</p>
<p>The Chef cookbook then installs some system wide packages, creates a virtual
environment, installs postgres and creates a database. These are not deploy
ready scripts but rather more hacky scripts to quickly bootstrap a development
env.</p>
<p>After saving, you can now do <code>vagrant up</code> this will take a while as it needs 
to download the ubuntu box to create the VM from. The time delay is mostly 
due to downloading of the box and also various packages like postgres so be 
warned if you have a slow or limited connection, this is likely to sum up to 
around 800mb or so.</p>
<p>After its finished, you should be able to do this.</p>
<div class="codehilite"><pre>vagrant ssh
workon project_name
ls -la
</pre></div>


<p>You will then be running from the virtual machine, but be in an activated 
Python virtual environment and in a directory that is mapped to the host 
machine. Thus the result of that should show the files for the directory that 
you started in. In my case I generally then need to do 
<code>pip install -r requirements.txt</code> and after that I can run the project - be it
a Django website, or something different.</p>
<p>After this you can pretty much carry on as normal. There are a few things to
note that may effect you. Any tools that rely on accessing the Python
interpreter will not work as its not on a remote machine, I don't have a need
for this so I've not worked out a solution. I simply use the python debugger
directly in the ssh session. Editors like pyDev will likely loose some 
functionality here but there may be a work around...</p>
<p>When using Django's runserver, you need to specify an IP address. I've created 
a alias to make this easier. This assumes you are still connected to the 
virtual machine but if not, cd into the project directory and run 
<code>vagrant ssh</code>. How awesome is it to not need to remember IP's or logins?</p>
<div class="codehilite"><pre>djr
<span class="c"># is the same as</span>
python manage.py runserver 0.0.0.0:8000
</pre></div>


<p>These shortcuts are best left for another post perhaps, but some more can be
seen in my <a href="https://github.com/d0ugal/dotfiles">dotfiles repository</a>.</p>
<p>To access the site itself, you'll then need to go to the IP address specified
in the config file. In this case the full path will be 
<code>http://33.33.00.10:8000</code> or since we have set the port forwarding in the 
config above you should be able to go to localhost:8000.</p>
<p>I'm still working out my complete workflow for vagrant but I'm using this
machine as a base point for much of my work and creating a new machine for 
each project. The best thing so far for me is a recorded development 
environment that I can use to create a VM now or in 6 months when revisiting 
an older project. My main problem at the moment is the effort required to 
make big changes (new configs, new recipes etc.) but this should get easier 
as I make more.</p>
<p>If you have any idea's or suggestions please let me know.</p>]]></content:encoded>
    </item>
    <item>
      <title>Blogofile - rethinking simple websites</title>
      <link>http://www.dougalmatthews.com/2011/02/22/blogofile-rethinking-simple-websites</link>
      <pubDate>Tue, 22 Feb 2011 19:25:00 GMT</pubDate>
      <category><![CDATA[python]]></category>
      <category><![CDATA[meta]]></category>
      <guid>YA_NYsJUf0vrtiiNbupvV8UGjEg=</guid>
      <description>Blogofile - rethinking simple websites</description>
      <content:encoded><![CDATA[<p>This website has gone through a number of different solutions over the years 
but during <a href="http://sitesprint.info/">SiteSprint</a> (II) I settled on a new site 
built with <a href="https://github.com/montylounge/django-mingus">Mingus</a>. Mingus 
offers a great feature set and is really well made (it makes use of many 
reusable apps that already exist). However, I was tired. Tired of blogging 
platforms, I needed to go back to basics.</p>
<p>So, step up <a href="http://www.blogofile.com/">Blogofile</a>. Firstly, what is it? 
Essentially it is a static site generator. You get to use Python, a templating 
language and a fairly simple but standard MVC architecture. However, the net 
result isn't a WSGI Python app, but rather a static media. A whole set of 
HTML and your other files like HTML and CSS too. One clever trick it uses is
to take advantage of folder structure and index.html files to create nice 
URL's.</p>
<p>As I use <a href="http://disqus.com/">Disqus</a> for all my comments the content of my 
blog rarely ever changes. I add or update a post now and then but on a day to 
day basis, it rarely changes. Rendering the page on each request is really 
inefficient and caching each page is overkill. My CV for example is stored as 
markdown on my site and rendered to html, a pdf or a doc as requested - now I 
only need to do this once. </p>
<p>For me, the main advantage comes from editing almost everything in vim. Now if 
I want to work on a post or do some maintenance I don't need to go through 
the Django admin and work in there. I can simply edit in vim and push back 
to the git repository. Which also means everything is version controlled and 
maintained in a sane way which fits into my workflow. </p>
<p>Hosting isn't really an issue for me with Django as with tools like 
<a href="http://docs.fabfile.org/">Fabric</a>, <a href="https://github.com/opscode/chef">Chef</a> and 
<a href="http://gunicorn.org/">Gunicorn</a> it doesn't need to be painful anymore. 
However, there is something to be said for the simplicity of deploying a 
completely static site. I don't need to worry about a wsgi server, a database 
or anything else and backing up isn't an issue. </p>
<p>I do have a few gripes with Blogfile though, they are fairly minor but nothin'
is perfect. I'm not a fan of <a href="http://www.makotemplates.org/">Mako</a>, I'd much 
rather edit <a href="http://jinja.pocoo.org/">Jinja2</a> templates. I'm pondering adding 
this functionality and the nice thing about blogofile is that it should be
fairly straightforward to do so. When working on your Blogofile site there is 
a handy server for testing locally but you need to rebuild manually to see the 
changes. This is a little annoying and I usually have two tabs open, one doing 
the rebuild every 10 seconds and one serving.</p>
<p>Incidentally, you can see the code for my Blogofile Blog on 
<a href="https://github.com/d0ugal/dm">github</a>.</p>]]></content:encoded>
    </item>
    <item>
      <title>Python Edinburgh</title>
      <link>http://www.dougalmatthews.com/articles/2010/aug/12/python-edinburgh/</link>
      <pubDate>Thu, 12 Aug 2010 19:25:00 BST</pubDate>
      <category><![CDATA[python]]></category>
      <category><![CDATA[django]]></category>
      <guid>http://www.dougalmatthews.com/articles/2010/aug/12/python-edinburgh/</guid>
      <description>Python Edinburgh</description>
      <content:encoded><![CDATA[<p>Python Edinburgh is user group for Pythonistas in (surprisingly) Edinburgh.
This is a kick start of a group that died out unfortunately and only met once 
this year.</p>
<p>Find out more at the new (but basic) <a href="http://www.pythonedinburgh.org/">website</a>
and <a href="http://twitter.com/pythonedinburgh">follow us on twitter</a> or 
<a href="http://mail.python.org/mailman/listinfo/edinburgh">join the mailing list</a>.</p>
<p>The group is going to be meeting on the 4th Tuesday of each month. The next 
being on the 24th August at <a href="http://www.bertsbar.co.uk/berts-bar/about/how-to-find-us.html">Bert's Bar</a>.</p>
<p>Hope to see some of you there - please let us know if your coming so we can 
get the numbers right.</p>]]></content:encoded>
    </item>
    <item>
      <title>Testing your first Django app</title>
      <link>http://www.dougalmatthews.com/articles/2010/jan/20/testing-your-first-django-app/</link>
      <pubDate>Wed, 20 Jan 2010 19:25:00 GMT</pubDate>
      <category><![CDATA[python]]></category>
      <category><![CDATA[testing]]></category>
      <category><![CDATA[django]]></category>
      <guid>http://www.dougalmatthews.com/articles/2010/jan/20/testing-your-first-django-app/</guid>
      <description>Testing your first Django app</description>
      <content:encoded><![CDATA[<p>This is my <strong>unofficial</strong> part five for the 
<a href="http://docs.djangoproject.com/en/1.1/intro/tutorial01/#intro-tutorial01">Django tutorial</a>. 
I've attempted to write this in a similar style to the Django 
documentation and hopefully this will be useful for those looking for 
the next step after the tutorial or trying out testing with django for 
the first time. Testing is something I think we can all do better, I 
certainly know I could do better testing my code sometimes.</p>
<p>If you don't have the polls app from the end of 
<a href="http://docs.djangoproject.com/en/1.1/intro/tutorial04/#intro-tutorial04">part four</a> 
and don't want to do it again you can grab it from 
<a href="https://github.com/d0ugal/django_tutorial/commits/P4">my github</a>.
The code added in this tutorial is also available in the <a href="https://github.com/d0ugal/django_tutorial/commits/master">master 
branch</a> 
of the repository.</p>
<hr />
<p>This tutorial begins where Tutorial 4 left off. We're continuing the 
Web-poll application and will focus on testing our application and 
proving that it works as expected.</p>
<h3>The testing environment</h3>
<p>Let's first look at how you run the tests, make sure you are in the 
mysite directory and run the command <code>python manage.py test</code>. You will
see output similar to this:</p>
<div class="codehilite"><pre><span class="n">Creating</span> <span class="n">test</span> <span class="n">database</span><span class="o">...</span>  
<span class="n">Creating</span> <span class="n">table</span> <span class="n">auth_permission</span>  
<span class="n">Creating</span> <span class="n">table</span> <span class="n">auth_group</span>  
<span class="n">Creating</span> <span class="n">table</span> <span class="n">auth_user</span>  
<span class="n">Creating</span> <span class="n">table</span> <span class="n">auth_message</span>  
<span class="n">Creating</span> <span class="n">table</span> <span class="n">django_admin_log</span>  
<span class="n">Creating</span> <span class="n">table</span> <span class="n">django_content_type</span>  
<span class="n">Creating</span> <span class="n">table</span> <span class="n">django_session</span>  
<span class="n">Creating</span> <span class="n">table</span> <span class="n">django_site</span>  
<span class="n">Creating</span> <span class="n">table</span> <span class="n">polls_poll</span>  
<span class="n">Creating</span> <span class="n">table</span> <span class="n">polls_choice</span>  
<span class="n">Installing</span> <span class="nb">index</span> <span class="k">for</span> <span class="n">auth</span><span class="o">.</span><span class="n">Permission</span> <span class="n">model</span>  
<span class="n">Installing</span> <span class="nb">index</span> <span class="k">for</span> <span class="n">auth</span><span class="o">.</span><span class="n">Message</span> <span class="n">model</span>  
<span class="n">Installing</span> <span class="nb">index</span> <span class="k">for</span> <span class="n">admin</span><span class="o">.</span><span class="n">LogEntry</span> <span class="n">model</span>  
<span class="n">Installing</span> <span class="nb">index</span> <span class="k">for</span> <span class="n">polls</span><span class="o">.</span><span class="n">Choice</span> <span class="n">model</span>  
<span class="o">...................................</span>  
<span class="o">------------------------------------------------------------------</span>  
<span class="n">Ran</span> <span class="mi">35</span> <span class="n">tests</span> <span class="n">in</span> <span class="mf">0.565</span><span class="n">s</span>

<span class="n">OK</span>  
<span class="n">Destroying</span> <span class="n">test</span> <span class="n">database</span><span class="o">...</span>
</pre></div>


<p>You have successfully ran the test suite for the project. If your output
doesn't look like this and it appears some of the tests have failed you
may want to take a moment and go back to make sure your project matches
the end of part 4. </p>
<p>When you run the test suite Django creates a new test database, 
synchronises your applications and loads any fixtures into the database.
Each test is then executed in turn wrapped inside a database transaction 
so it can be rolled back after each test is completed. At the end of the 
tests Django destroys the test database for you.</p>
<p>What did we just test? <code>manage.py test</code> runs all the tests for each of
the applications in your INSTALLED_APPS setting. All of the 
django.contrib applications ship with tests, as should all of yours. 
This is great as we can use this to test that the contrib applications 
are all configured correctly.</p>
<p>Run the same command again but include the verbose flag so we can see 
more information about what actually just happened. To do this run the 
command <code>python manage.py test -v 2</code>. There will be more output this 
time showing each of the tests that were carried out with the test 
outcome.</p>
<h3>What is a test?</h3>
<p>With Django (and Python in general) there are two main ways to write 
tests for your projects test suite; doctests and unit tests. In Django 
both of these use the standard python modules 
<a href="http://docs.python.org/library/doctest.html">doctest</a> and 
<a href="http://docs.python.org/library/unittest.html">unittest</a>. Doctests are
written in Python docstrings and unit test are defined with classes. Good
generic examples and explanations can be found on both of these in the
Django documentation 
<a href="http://docs.djangoproject.com/en/1.1/topics/testing/#writing-doctests">here</a>
and <a href="http://docs.djangoproject.com/en/1.1/topics/testing/#writing-unit-tests">here</a>.
If your unsure which to use, 
<a href="http://docs.djangoproject.com/en/dev/topics/testing/#which-should-i-use">read this</a>.</p>
<p>For the sake of being succinct we  will focus on unit tests in this 
tutorial.</p>
<h3>Writing a test</h3>
<p>In part one it was noted in passing that when you created your polls 
application the file <code>tests.py</code> was created. The more adventurous of you
will have taken a look and seen a simple (but redundant) example
unit test and doctest. Django's test runner by default runs any tests 
that you create in <code>tests.py</code> in the application package. This is 
similar to the auto detection of admin configurations in the <code>admin.py</code>
files. </p>
<p>To run only the tests for a specific application run the following 
command <code>python manage.py test polls</code>. This will run the two 
default tests that are present in the polls application we created 
earlier in the tutorial.</p>
<p>Delete the contents of the tests.py file and add the following test 
case.</p>
<div class="codehilite"><pre><span class="kn">from</span> <span class="nn">datetime</span> <span class="kn">import</span> <span class="n">datetime</span>

<span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">TestCase</span>

<span class="kn">from</span> <span class="nn">mysite.polls.models</span> <span class="kn">import</span> <span class="n">Poll</span>

<span class="k">class</span> <span class="nc">PollTest</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>

    <span class="k">def</span> <span class="nf">setUp</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">question</span><span class="o">=</span><span class="s">&quot;What is your favourite colour?&quot;</span>
        <span class="n">now</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">()</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">poll</span> <span class="o">=</span> <span class="n">Poll</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">question</span><span class="o">=</span><span class="n">question</span><span class="p">,</span> <span class="n">pub_date</span><span class="o">=</span><span class="n">now</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">poll</span><span class="o">.</span><span class="n">choice_set</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">choice</span><span class="o">=</span><span class="s">&quot;Red&quot;</span><span class="p">,</span> <span class="n">votes</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">poll</span><span class="o">.</span><span class="n">choice_set</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">choice</span><span class="o">=</span><span class="s">&quot;Bue&quot;</span><span class="p">,</span> <span class="n">votes</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">poll</span><span class="o">.</span><span class="n">choice_set</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">choice</span><span class="o">=</span><span class="s">&quot;Green&quot;</span><span class="p">,</span> <span class="n">votes</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">test_models</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">poll</span><span class="o">.</span><span class="n">choice_set</span><span class="o">.</span><span class="n">all</span><span class="p">()</span><span class="o">.</span><span class="n">count</span><span class="p">(),</span> <span class="mi">3</span><span class="p">)</span>
</pre></div>


<p>In this test case the <code>setUp</code> method creates a new poll and adds three 
choices to the poll. Remember since the test runner creates its own 
database there is no data yet. <code>setUp</code> is called at the start of each 
test defined within your test case class. The test verifies that the 
number of choices in the created poll is equal to 3. A test is a method 
that starts with <code>test_</code> and is a property of a class extending 
TestCase.</p>
<p>Try playing with this and making the test fail by changing the number or
adding/removing choices. The test can also end with an error result if 
there is an uncaught exception, this can be done by adding 
<code>Poll.objects.get(pk=2)</code> as there isn't a poll with that id. It's 
worth familiarising yourself with the different possible test results.</p>
<p>When running your the tests by running <code>python manage.py test polls</code> 
the output displays a single <code>.</code> for each test that passes. If a test 
fails a <code>F</code> will be displated and if there is an error <code>E</code> will be 
displayed. A failure is when one of the assertions fails and an error
happens when there is an uncaught exception while running the test.</p>
<p>Let's add another test case that does something more useful.</p>
<div class="codehilite"><pre><span class="c"># ...</span>
<span class="kn">from</span> <span class="nn">django.test</span> <span class="kn">import</span> <span class="n">Client</span>

<span class="kn">from</span> <span class="nn">mysite.polls.models</span> <span class="kn">import</span> <span class="n">Poll</span><span class="p">,</span> <span class="n">Choice</span>

<span class="k">class</span> <span class="nc">PollTest</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>

    <span class="c"># ...</span>

    <span class="k">def</span> <span class="nf">test_voting</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">c</span> <span class="o">=</span> <span class="n">Client</span><span class="p">()</span>
        <span class="c"># Perform a vote on the poll by mocking a POST request.</span>
        <span class="n">response</span> <span class="o">=</span> <span class="n">c</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="s">&#39;/polls/1/vote/&#39;</span><span class="p">,</span> <span class="p">{</span><span class="s">&#39;choice&#39;</span><span class="p">:</span> <span class="s">&#39;1&#39;</span><span class="p">,})</span>
        <span class="c"># In the vote view we redirect the user, so check the </span>
        <span class="c"># response status code is 302.</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">status_code</span><span class="p">,</span> <span class="mi">302</span><span class="p">)</span>
        <span class="c"># Get the choice and check there is now one vote.</span>
        <span class="n">choice</span> <span class="o">=</span> <span class="n">Choice</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">choice</span><span class="o">.</span><span class="n">votes</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
</pre></div>


<p>In this example we make use of the Django test client. Using the client
we are able to simulate requests without the need for a server, rather
the request object is mocked and the view is invoked with the mock 
request. In this test we create a POST request that mocks a vote on the 
poll and then checks both the status_code of the response (to check we 
have been redirected) and verifies the number of votes has increased.</p>
<h3>Test driven development</h3>
<p>Test driven development is the practice of writing tests that fail and
show what the system should do and then write or change the code to 
make the test(s) pass.</p>
<p>Next we want to add some Ajax to our application, to do this we want to
be able to call the vote with an Ajax request and recieve some simple
information we can work with rather than the full html response. First 
we will write the test for how we want this to work. We want the system
to return <code>'1'</code> on a valid vote and <code>'0'</code> on an invalid vote in the http
response.</p>
<div class="codehilite"><pre><span class="k">class</span> <span class="nc">PollTest</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>

    <span class="c"># ...</span>

    <span class="k">def</span> <span class="nf">test_ajax_vote</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>

        <span class="n">c</span> <span class="o">=</span> <span class="n">Client</span><span class="p">()</span>

        <span class="c"># Extra parameters to make this a Ajax style request.</span>
        <span class="n">kwargs</span> <span class="o">=</span> <span class="p">{</span><span class="s">&#39;HTTP_X_REQUESTED_WITH&#39;</span><span class="p">:</span><span class="s">&#39;XMLHttpRequest&#39;</span><span class="p">}</span>

        <span class="c"># A valid vote</span>
        <span class="n">response</span> <span class="o">=</span> <span class="n">c</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="s">&#39;/polls/1/vote/&#39;</span><span class="p">,</span> <span class="p">{</span><span class="s">&#39;choice&#39;</span><span class="p">:</span> <span class="s">&#39;1&#39;</span><span class="p">,},</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">status_code</span><span class="p">,</span> <span class="mi">200</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">content</span><span class="p">,</span> <span class="s">&#39;1&#39;</span><span class="p">)</span>

        <span class="c"># A invalid vote - choice doesn&#39;t exist</span>
        <span class="n">response</span> <span class="o">=</span> <span class="n">c</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="s">&#39;/polls/1/vote/&#39;</span><span class="p">,</span> <span class="p">{</span><span class="s">&#39;choice&#39;</span><span class="p">:</span> <span class="s">&#39;10&#39;</span><span class="p">,},</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">status_code</span><span class="p">,</span> <span class="mi">200</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">content</span><span class="p">,</span> <span class="s">&#39;0&#39;</span><span class="p">)</span>

        <span class="c"># An invalid vote - poll doesn&#39;t exist</span>
        <span class="n">response</span> <span class="o">=</span> <span class="n">c</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="s">&#39;/polls/2/vote/&#39;</span><span class="p">,</span> <span class="p">{</span><span class="s">&#39;choice&#39;</span><span class="p">:</span> <span class="s">&#39;1&#39;</span><span class="p">,},</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">status_code</span><span class="p">,</span> <span class="mi">404</span><span class="p">)</span>
</pre></div>


<p>Add this to your tests and then run the test suite. You should get 
output similar to this; </p>
<div class="codehilite"><pre><span class="n">F</span><span class="o">..</span>
<span class="o">===================================================================</span>
<span class="n">FAIL:</span> <span class="n">test_ajax_vote</span> <span class="p">(</span><span class="n">mysite</span><span class="o">.</span><span class="n">polls</span><span class="o">.</span><span class="n">tests</span><span class="o">.</span><span class="n">PollTest</span><span class="p">)</span>
<span class="o">-------------------------------------------------------------------</span>
<span class="n">Traceback</span> <span class="p">(</span><span class="n">most</span> <span class="n">recent</span> <span class="n">call</span> <span class="k">last</span><span class="p">):</span>
  <span class="n">File</span> <span class="s">&quot;/mysite/polls/tests.py&quot;</span><span class="p">,</span> <span class="n">line</span> <span class="mi">41</span><span class="p">,</span> <span class="n">in</span> <span class="n">test_ajax_vote</span>
    <span class="n">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">status_code</span><span class="p">,</span> <span class="mi">200</span><span class="p">)</span>
<span class="n">AssertionError:</span> <span class="mi">302</span> <span class="o">!=</span> <span class="mi">200</span>

<span class="o">-------------------------------------------------------------------</span>
</pre></div>


<p>We have not updated our view, so rather than returning something useful
for the Ajax request the server has returned a redirect to the results 
page. This then means the test fails at the first hurdle when we check 
the response code. </p>
<p>Now all we need to do is update the code in the vote view to make the 
tests pass. Change your view so it matches the following.</p>
<div class="codehilite"><pre><span class="k">def</span> <span class="nf">vote</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">poll_id</span><span class="p">):</span>
    <span class="n">p</span> <span class="o">=</span> <span class="n">get_object_or_404</span><span class="p">(</span><span class="n">Poll</span><span class="p">,</span> <span class="n">pk</span><span class="o">=</span><span class="n">poll_id</span><span class="p">)</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">selected_choice</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">choice_set</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="n">request</span><span class="o">.</span><span class="n">POST</span><span class="p">[</span><span class="s">&#39;choice&#39;</span><span class="p">])</span>
    <span class="k">except</span> <span class="p">(</span><span class="ne">KeyError</span><span class="p">,</span> <span class="n">Choice</span><span class="o">.</span><span class="n">DoesNotExist</span><span class="p">):</span>
        <span class="c"># bad vote, return &#39;0&#39;</span>
        <span class="k">if</span> <span class="n">request</span><span class="o">.</span><span class="n">is_ajax</span><span class="p">():</span>
            <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s">&quot;0&quot;</span><span class="p">)</span>
        <span class="c"># Redisplay the poll voting form.</span>
        <span class="k">return</span> <span class="n">render_to_response</span><span class="p">(</span><span class="s">&#39;polls/poll_detail.html&#39;</span><span class="p">,</span> <span class="p">{</span>
            <span class="s">&#39;object&#39;</span><span class="p">:</span> <span class="n">p</span><span class="p">,</span>
            <span class="s">&#39;error_message&#39;</span><span class="p">:</span> <span class="s">&quot;You didn&#39;t select a choice.&quot;</span><span class="p">,</span>
        <span class="p">})</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">selected_choice</span><span class="o">.</span><span class="n">votes</span> <span class="o">+=</span> <span class="mi">1</span>
        <span class="n">selected_choice</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
        <span class="c"># vote saved, return &#39;1&#39;</span>
        <span class="k">if</span> <span class="n">request</span><span class="o">.</span><span class="n">is_ajax</span><span class="p">():</span>
            <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s">&quot;1&quot;</span><span class="p">)</span>
        <span class="c"># Always return an HttpResponseRedirect after successfully dealing</span>
        <span class="c"># with POST data. This prevents data from being posted twice if a</span>
        <span class="c"># user hits the Back button.</span>
        <span class="k">return</span> <span class="n">HttpResponseRedirect</span><span class="p">(</span><span class="n">reverse</span><span class="p">(</span><span class="s">&#39;poll_results&#39;</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">id</span><span class="p">,)))</span>
</pre></div>


<p>Re-run the test suite and it should now pass. You have successfully
written your first tests for the polls app and even done a little bit of
test driven development.</p>
<h3>What next and further reading</h3>
<p>Now you should have a good understanding of testing basics and hopefully
a better idea of how to test your applications. Testing is really quite 
straight forward much of the time, you simply write a bit more code to
make sure the code you have actually works - it's invaluable when you 
get into the routine and have a comprehensive test suite. </p>
<p>Here are a few resources that you should look at for taking the next 
step. </p>
<ul>
<li>Python <a href="http://docs.python.org/library/unittest.html">unit test documentation</a></li>
<li>Python <a href="http://docs.python.org/library/doctest.html">doctest documentation</a></li>
<li>The Django <a href="http://docs.djangoproject.com/en/dev/topics/testing/">testing documentation</a></li>
<li>Eric Holscher's awesome <a href="http://djangocon.blip.tv/file/3039829/">DjangoCon talk about testing</a></li>
</ul>
<hr />
<blockquote>
<p>"Code without tests is broken as designed"<br />
- Jacob Kaplan-Moss</p>
</blockquote>
<p>Leaving you with those wise words I trust you will now take as much 
advantage of testing as you can and strive to create good tests for all
your code. </p>]]></content:encoded>
    </item>
    <item>
      <title>Fun with Balls</title>
      <link>http://www.dougalmatthews.com/articles/2010/jan/8/fun-with-balls/</link>
      <pubDate>Fri, 08 Jan 2010 19:25:00 GMT</pubDate>
      <category><![CDATA[javascript]]></category>
      <guid>http://www.dougalmatthews.com/articles/2010/jan/8/fun-with-balls/</guid>
      <description>Fun with Balls</description>
      <content:encoded><![CDATA[<p>As a simple for-fun ritual when I learn a new language I like to create
a simple very basic application that has some 2D balls (spheres if you
prefer) bouncing on the screen and then I would mess with settings and
effects, fairly basic stuff. It's not really all that exciting but its
fun to write and covers enough things to help you get a decent  start
with the language.</p>
<h4>JavaScript Balls</h4>
<p>I've done this with a few languages, the first was with Visual Basic 6
at college and since then I've done it again with Perl and JavaScript. I
did start one in Java but don't think I ever finished. I've never got
around to creating a Python port and I'm going to have to change that
but for the moment here it is in JavaScript.</p>
<blockquote>
<p><strong> <a href="/media/blog/balls/">See it in action here</a> </strong></p>
<p>Note, you will need a browser that is capable of handling &lt;canvas&gt;
so in other words - not Internet Explorer 6. Also I'm afraid the
size is fixed so it wont look nice on small resolutions.</p>
</blockquote>
<p>The code is really shoddy as its one of the first things I coded in
JavaScript. I'd like to re-write it at some point to compare how I do it
now that I feel comfortable with the language.</p>
<p>I remember when I wrote this my computer wasn't fast enough to render it
very smoothly and the only browser it worked on was FireFox (and
probably Safari but I didn't, and still don't, have a mac). I'm glad to
see how much the browser landscape has changed since then.</p>
<h4>The Others</h4>
<p>I've totally lost the perl implementation - I think I probably left it
on a university computer somewhere. I've got the VB6 code but I don't
have visual studio (installed) anymore and I don't have a floppy drive to
access it!</p>
<p>My Python version, well I think I might do that later if I have time.
I've done very little GUI code with Python so it would make for a fun
exercise.</p>
<h4>Whats changed?</h4>
<p>I find it interesting that as programmers we can often find our way
around an unfamiliar language enough to get things working but generally
you don't take advantage of that languages features. I guess this could
be likened to writing in a language you don't really know (anything but
english in my case) and stumbling with grammar and spelling<sup id="fnref:1"><a href="#fn:1" rel="footnote">1</a></sup>.</p>
<p>Looking back, the most interesting thing is probably how different I
would approach the problem now. I used Prototype, a library I don't
really have anything against but it doesn't really fit with how I see
JavaScript now as it adds various features that make it feel more like a
'traditional' object oriented language with classes and classical
inheritance. The code relies on global objects and has events written
into the HTML.</p>
<p>Quite frankly most of the code is rubbish but thats one of the ways you
learn! Given the task now I would use jQuery and might consider using some
HTML5 or CSS3 features. That actually sounds quite fun - I sense a
mini project coming up.</p>
<div class="footnote">
<hr />
<ol>
<li id="fn:1">
<p>Something I'm particularly fond of doing.
&#160;<a href="#fnref:1" rev="footnote" title="Jump back to footnote 1 in the text">&#8617;</a></p>
</li>
</ol>
</div>]]></content:encoded>
    </item>
    <item>
      <title>Nicer dynamic forms in django</title>
      <link>http://www.dougalmatthews.com/articles/2009/dec/16/nicer-dynamic-forms-django/</link>
      <pubDate>Wed, 16 Dec 2009 19:25:00 GMT</pubDate>
      <category><![CDATA[python]]></category>
      <category><![CDATA[django]]></category>
      <guid>http://www.dougalmatthews.com/articles/2009/dec/16/nicer-dynamic-forms-django/</guid>
      <description>Nicer dynamic forms in django</description>
      <content:encoded><![CDATA[<p>I used to make dynamic forms for Django in very bad way, I'm happy to admit 
that now as I've improved my process.</p>
<p>Basically the solution is to use <code>type()</code> as I'm sure many of you know. If your 
doing that already there isn't much for you here. If your messing around with
'<code>self.fields["name"]</code>' in your forms then read on.</p>
<p>Lets take a simple use case; a quiz system. You can think of it like who
wants to be a millionaire. We will have a Question with four possible 
answers. So two models...</p>
<div class="codehilite"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Question</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">test</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">128</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">Answer</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">question</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Question</span><span class="p">)</span>
    <span class="n">test</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">20</span><span class="p">)</span>
    <span class="n">is_correct</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">BooleanField</span><span class="p">(</span><span class="n">default</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span>
</pre></div>


<p>Basically we want a form that stores both the question and the 
answers and checks the answer is a valid choice. You could do it this way.</p>
<div class="codehilite"><pre><span class="kn">from</span> <span class="nn">django</span> <span class="kn">import</span> <span class="n">forms</span>

<span class="k">class</span> <span class="nc">QuizForm</span><span class="p">(</span><span class="n">forms</span><span class="o">.</span><span class="n">Form</span><span class="p">):</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span><span class="n">question</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="nb">super</span><span class="p">(</span><span class="n">QuizForm</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>

        <span class="bp">self</span><span class="o">.</span><span class="n">fields</span><span class="p">[</span><span class="s">&#39;question&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">IntegerField</span><span class="p">(</span><span class="n">widget</span><span class="o">=</span> \
            <span class="n">forms</span><span class="o">.</span><span class="n">HiddenInput</span><span class="p">,</span> <span class="n">initial</span><span class="o">=</span><span class="n">question</span><span class="o">.</span><span class="n">id</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">fields</span><span class="p">[</span><span class="s">&#39;answers&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">ModelChoiceField</span><span class="p">(</span><span class="n">queryset</span><span class="o">=</span> \
            <span class="n">question</span><span class="o">.</span><span class="n">answers_set</span><span class="p">)</span>
</pre></div>


<p>Now in this example that's actually not too bad. It's still a bit hacky 
as we tap into the fields dict after calling the parents constructor. I
have a variant of this where I moved the field generation out of the 
<code>__init__</code> but that doesn't really change much - just gives you the 
option of calling it later. Remember this is a very simple example, 
what if you need to generate a class based on 20 parameters?</p>
<p>So how can we solve this with <code>type()</code>? Well lets step back a minute and 
quickly refresh ourselves with the builtin function <code>type()</code>. There are 
two ways to use this function the first is by calling <code>type(object)</code>
and the type of that object is returned. The second is to create
classes at runtime by using <code>type()</code> as a class constructor.</p>
<p>First lets look at an example that has exactly with the same result
as the previous example.</p>
<div class="codehilite"><pre><span class="k">def</span> <span class="nf">quiz_form_factory</span><span class="p">(</span><span class="n">question</span><span class="p">):</span>

    <span class="n">properties</span> <span class="o">=</span> <span class="p">{</span>
        <span class="s">&#39;question&#39;</span> <span class="p">:</span> <span class="n">forms</span><span class="o">.</span><span class="n">IntegerField</span><span class="p">(</span><span class="n">widget</span><span class="o">=</span><span class="n">forms</span><span class="o">.</span><span class="n">HiddenInput</span><span class="p">,</span> \
            <span class="n">initial</span><span class="o">=</span><span class="n">question</span><span class="o">.</span><span class="n">id</span><span class="p">),</span>
        <span class="s">&#39;answers&#39;</span> <span class="p">:</span> <span class="n">forms</span><span class="o">.</span><span class="n">ModelChoiceField</span><span class="p">(</span><span class="n">queryset</span><span class="o">=</span> \
            <span class="n">question</span><span class="o">.</span><span class="n">answers_set</span><span class="p">)</span>
    <span class="p">}</span>

    <span class="k">return</span> <span class="nb">type</span><span class="p">(</span><span class="s">&#39;QuizForm&#39;</span><span class="p">,</span> <span class="p">(</span><span class="n">forms</span><span class="o">.</span><span class="n">Form</span><span class="p">,),</span> <span class="n">properties</span><span class="p">)</span>
</pre></div>


<p>And there we go, it's as simple as that. When using <code>type()</code> to 
construct classes it takes three parameters 
<code>type(class_name, base_classes_tuple, properties_dict)</code>; the name 
of the class, the base classes it inherits from and the properties the 
created class will have.</p>
<p>Besides the above implementation the usage is slightly different.</p>
<div class="codehilite"><pre><span class="c"># start with a random question</span>
<span class="n">question</span> <span class="o">=</span> <span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;?&#39;</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span>

<span class="c"># method A</span>
<span class="n">quiz_form</span> <span class="o">=</span> <span class="n">QuizForm</span><span class="p">(</span><span class="n">question</span><span class="p">)</span>
<span class="c"># or with POST data</span>
<span class="n">quiz_form</span> <span class="o">=</span> <span class="n">QuizForm</span><span class="p">(</span><span class="n">question</span><span class="p">,</span> <span class="n">request</span><span class="o">.</span><span class="n">POST</span><span class="p">)</span>

<span class="c"># method B</span>
<span class="n">QuizForm</span> <span class="o">=</span> <span class="n">quiz_form_factory</span><span class="p">(</span><span class="n">question</span><span class="p">)</span>
<span class="n">quiz_form</span> <span class="o">=</span> <span class="n">QuizForm</span><span class="p">()</span>
<span class="c"># or with POST data</span>
<span class="n">quiz_form</span> <span class="o">=</span> <span class="n">QuizForm</span><span class="p">(</span><span class="n">request</span><span class="o">.</span><span class="n">POST</span><span class="p">)</span>
</pre></div>


<p>Again, perhaps I should have chosen a more complex example as the
the first method may not look to bad and  requires less code but its 
not <em>nice</em>. Using this approach basically class initialisation with the 
preparation and modification of said class. The second is  much 
clearer as you explicitly generate a class then create an instance of it.</p>
<p>The main advantage for me is the clarify this gives you and the code 
used to make it dynamic is clear and better structured. It's also 
worth mentioning that with a <code>type()</code> constructed form it behaves 
exactly like a regular form after creation where with method A the 
developer needs to pass in the question instance each time and be aware
of this requirement and how it varies from a typical Django style form.</p>]]></content:encoded>
    </item>
    <item>
      <title>Changing default storage engine in MySQL</title>
      <link>http://www.dougalmatthews.com/articles/2008/sep/3/changing-default-storage-engine-in-mysql/</link>
      <pubDate>Wed, 03 Sep 2008 19:25:00 BST</pubDate>
      <category><![CDATA[mysql]]></category>
      <guid>http://www.dougalmatthews.com/articles/2008/sep/3/changing-default-storage-engine-in-mysql/</guid>
      <description>Changing default storage engine in MySQL</description>
      <content:encoded><![CDATA[<p>It took me a while to find the answer to this, so I thought I'd share it to 
avoid anybody else wasting time with this. I needed to change the default
storage engine so Django would use innoDB rather than MyISAM. Otherwise, it 
seemed to take the default.</p>
<p>You first need to locate the MySQL config file named my.cnf. On CentOS 5.2 it 
is located at /etc/my.cnf but this will probably vary across platforms.</p>
<p>Then in that file find the [mysqld] and add add the following line below it
as shown below.</p>
<div class="codehilite"><pre><span class="k">[mysqld]</span>
<span class="na">default-storage-engine</span> <span class="o">=</span> <span class="s">innodb</span>
</pre></div>


<p>Finally, make sure you restart MySQL.</p>
<div class="codehilite"><pre><span class="n">service</span> <span class="n">mysqld</span> <span class="n">restart</span>
</pre></div>


<p>It's pretty easy wen you know how, and you'll now had transactional tables by
default.</p>
<p>Alterantivaley though, you could use a 
<a href="www.postgresql.org">much better database</a>.</p>]]></content:encoded>
    </item>
    <item>
      <title>JavaScript - Detecting Caps lock</title>
      <link>http://www.dougalmatthews.com/articles/2008/jul/2/javascript-detecting-caps-lock/</link>
      <pubDate>Wed, 02 Jul 2008 19:25:00 BST</pubDate>
      <category><![CDATA[javascript]]></category>
      <guid>http://www.dougalmatthews.com/articles/2008/jul/2/javascript-detecting-caps-lock/</guid>
      <description>JavaScript - Detecting Caps lock</description>
      <content:encoded><![CDATA[<p>I wanted to see if you could detect caps lock in JavaScript. Why? As a small 
usability touch, basically alerting users that caps lock is enabled when they 
are entering passwords for example. I’ve wrapped up the logic in a simple 
function that can help you detect caps lock on a key press.</p>
<p>Sorry. Demo no longer exists, just copy the code and it should work straight off ;)</p>
<div class="codehilite"><pre><span class="kd">function</span> <span class="nx">isCapslock</span><span class="p">(</span><span class="nx">e</span><span class="p">){</span>

    <span class="nx">e</span> <span class="o">=</span> <span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="o">?</span> <span class="nx">e</span> <span class="o">:</span> <span class="nb">window</span><span class="p">.</span><span class="nx">event</span><span class="p">;</span>

    <span class="kd">var</span> <span class="nx">charCode</span> <span class="o">=</span> <span class="kc">false</span><span class="p">;</span>
    <span class="k">if</span> <span class="p">(</span><span class="nx">e</span><span class="p">.</span><span class="nx">which</span><span class="p">)</span> <span class="p">{</span>
        <span class="nx">charCode</span> <span class="o">=</span> <span class="nx">e</span><span class="p">.</span><span class="nx">which</span><span class="p">;</span>
    <span class="p">}</span> <span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="nx">e</span><span class="p">.</span><span class="nx">keyCode</span><span class="p">)</span> <span class="p">{</span>
        <span class="nx">charCode</span> <span class="o">=</span> <span class="nx">e</span><span class="p">.</span><span class="nx">keyCode</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="kd">var</span> <span class="nx">shifton</span> <span class="o">=</span> <span class="kc">false</span><span class="p">;</span>
    <span class="k">if</span> <span class="p">(</span><span class="nx">e</span><span class="p">.</span><span class="nx">shiftKey</span><span class="p">)</span> <span class="p">{</span>
        <span class="nx">shifton</span> <span class="o">=</span> <span class="nx">e</span><span class="p">.</span><span class="nx">shiftKey</span><span class="p">;</span>
    <span class="p">}</span> <span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="nx">e</span><span class="p">.</span><span class="nx">modifiers</span><span class="p">)</span> <span class="p">{</span>
        <span class="nx">shifton</span> <span class="o">=</span> <span class="o">!!</span><span class="p">(</span><span class="nx">e</span><span class="p">.</span><span class="nx">modifiers</span> <span class="o">&amp;</span> <span class="mi">4</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">if</span> <span class="p">(</span><span class="nx">charCode</span> <span class="o">&gt;=</span> <span class="mi">97</span> <span class="o">&amp;&amp;</span> <span class="nx">charCode</span> <span class="o">&lt;=</span> <span class="mi">122</span> <span class="o">&amp;&amp;</span> <span class="nx">shifton</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">return</span> <span class="kc">true</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">if</span> <span class="p">(</span><span class="nx">charCode</span> <span class="o">&gt;=</span> <span class="mi">65</span> <span class="o">&amp;&amp;</span> <span class="nx">charCode</span> <span class="o">&lt;=</span> <span class="mi">90</span> <span class="o">&amp;&amp;</span> <span class="o">!</span><span class="nx">shifton</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">return</span> <span class="kc">true</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">return</span> <span class="kc">false</span><span class="p">;</span>

<span class="p">}</span>
</pre></div>]]></content:encoded>
    </item>
  </channel>
</rss>

