<?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 Usware Blog - Django Web Development &#187; python</title>
	<atom:link href="http://uswaretech.com/blog/category/python/feed/" rel="self" type="application/rss+xml" />
	<link>http://uswaretech.com/blog</link>
	<description>Building Amazing Webapps</description>
	<lastBuildDate>Tue, 08 Jun 2010 14:59:46 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Doing things with Django models &#8211; aka &#8211; Django models tutorial</title>
		<link>http://uswaretech.com/blog/2010/01/django-models-tutorial/</link>
		<comments>http://uswaretech.com/blog/2010/01/django-models-tutorial/#comments</comments>
		<pubDate>Mon, 18 Jan 2010 05:00:17 +0000</pubDate>
		<dc:creator>shabda</dc:creator>
				<category><![CDATA[django]]></category>
		<category><![CDATA[models]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://uswaretech.com/blog/?p=891</guid>
		<description><![CDATA[Django abstracts most of the actions you would be doing with the Database. What it doesn&#8217;t abstracts, and doesn&#8217;t try to abstract is the Database modelling part. This is a quick tutorial describing to how model your data in Django models.py, and how to access and modify them. Consider a hypothetical HR department, which wants [...]


Related posts:<ol><li><a href='http://uswaretech.com/blog/2009/08/django-aggregation-tutorial/' rel='bookmark' title='Permanent Link: Django aggregation tutorial'>Django aggregation tutorial</a></li>
<li><a href='http://uswaretech.com/blog/2010/03/the-rails-and-django-models-layer-rosseta-stone/' rel='bookmark' title='Permanent Link: The Rails and Django models layer Rosseta stone'>The Rails and Django models layer Rosseta stone</a></li>
<li><a href='http://uswaretech.com/blog/2008/10/dynamic-forms-with-django/' rel='bookmark' title='Permanent Link: Dynamic forms with Django'>Dynamic forms with Django</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p></p><p>Django abstracts most of the actions you would be doing with the Database.
What it doesn&#8217;t abstracts, and doesn&#8217;t try to abstract is the Database modelling part. This is a quick tutorial
describing to how model your data in Django models.py, and how to access and modify them.</p>

<p>Consider a hypothetical HR department, which wants you to build an application to track and manage their processes.
They have employees who work for a department, contractors who work for multiple department. Let&#8217;s see how you
you would do that in Django.</p>

<pre><code>from django.db import models

class Employee(models.Model):
    name = models.CharField(max_length = 100)
    department = models.ForeignKey("Department")

class Department(models.Model):
    name = models.CharField(max_length = 100)

class EmployeeHistory(models.Model):
    employee = models.OneToOneField(Employee)
    date_joined = models.DateField()
    marital_status = models.BooleanField()

class Contactor(models.Model):
    name = models.CharField(max_length = 100)
    departments = models.ManyToManyField(Department)
</code></pre>

<p>Let&#8217;s see the type of relationship we created here.</p>

<p>An <code>Employee</code> has a Many-to-one relationship with <code>Department</code>, (i.e. One department will have many
<code>Employee</code>, but one employee will have a single departments.)</p>

<p>So <code>Employee</code> has a field <code>department = models.ForeignKey("Department")</code>. See that the <code>ForeignKey</code> field
was added on the class which has in <em>many</em>. In database, this creates a FK from in <code>Employee</code> table which refernces
<code>Departments</code>.</p>

<p>A <code>Contractor</code> has many-to-many relationships with <code>Department</code>, so it has a <code>ManyToMany</code> field. This field can be created
on either classes. At a database level this creates a new table which has a FK to both the tables.</p>

<p>A <code>Employee</code> has one-to-one relationship with <code>EmployeeHistory</code>. The thing to note here is that whatever we could do with
OneToOneField, we can do by including the fields in the Other Class directly. However when there are fields which are only rarely
needed with a given model, it is useful to separate them via a one-to-one field. The one to one field can be on either class.</p>

<h4>Accessing objects.</h4>

<h5>Getting a specific employee.</h5>

<pre><code>Employee.objects.get(pk = someval)
Employee.objects.get(name= someval)
</code></pre>

<h5>Given an department get all employees.</h5>

<pre><code>department.employee_set.all()
</code></pre>

<p>The <code>department</code> gets an attribute name <code>&lt;FKClass&gt;_set</code>.</p>

<p>Given an employee, get all colleagues.</p>

<pre><code>employee.department.employee_set.objects.all()
</code></pre>

<p>To get siblings, get parents, and get all children.</p>

<p>Given an department, get number of employees.</p>

<pre><code>department.employee_set.all().count()
</code></pre>

<p>Ok so the HR department bosses are happy with what they see, and ask you to track this data,
who is the manager of each employee, who is the HOD of each department and when did each employee took leave.</p>

<pre><code>from django.db import models

class Employee(models.Model):
    name = models.CharField(max_length = 100)
    manager = models.ForeignKey("self", blank = True, null = True)
    department = models.ForeignKey("Department")

class Department(models.Model):
    hod = models.ForeignKey("Employee")
    name = models.CharField(max_length = 100)

class EmployeeHistory(models.Model):
    employee = models.OneToOneField(Employee)
    date_joined = models.DateField()
    marital_status = models.BooleanField()

class Contactors(models.Model):
    name = models.CharField(max_length = 100)
    departments = models.ManyToManyField(Department)


class EmployeeLeave(models.Model):
    leave_taken = models.DateField()
    employee = models.ForeignKey(Employee)
</code></pre>

<p>So we now have new fields <code>hod = models.OneToOneField("Employee")</code> in department and
<code>manager = models.ForeignKey("self", blank = True, null = True)</code> and a new model <code>EmployeeLeave</code>. Let su see
the new realtions,</p>

<p>As one <code>Department</code> will have one <code>Employee</code> as hod, and <code>Employee</code> can head at max one <code>Department</code>, we have a one to one relationship<br />
As many <code>Employee</code> will report to another <code>Employee</code>, so we have a FK on <code>Employee</code>, referencing <code>self</code>.
As <code>Employee</code> will take many <code>EmployeeLeave</code>, <code>EmployeeLeave</code> has a FK to <code>Epployee</code></p>

<p>Let us see some queries.</p>

<p>Get all leaves taken by an employee this year</p>

<pre><code>import datetime
today = datetime.date.today()
start_of_year = datetime.datetime(today.year, 1, 1)
leaves_taken = employee.employeeleave_set.filter(leave_taken__gt=start_of_year, leave_taken__lt = today)
</code></pre>

<p>Get a list of all HODs.</p>

<pre><code>#As there are going to be as many Employees as departments
departments = Department.objects.all()
employees = [department.hod for department in departments]
</code></pre>

<p>Get a list of all departments a contractor works for.</p>

<pre><code>contractor.department_set.all()
</code></pre>

<p>Get a list of all contractor who work for a department.</p>

<pre><code>department.contractor_set.all()
</code></pre>

<p>Note that each side of a many to many relationship get a Manager.</p>

<p>List of all managers in a given department.</p>

<pre><code>Todo#(Can't think of any one query way to do this. If you know, let me know <img src='http://uswaretech.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  )
</code></pre>

<p>List of all leaves taken in a given department.</p>

<pre><code>EmployeeLeave.objects.filter(employee__department = department)
</code></pre>

<p>None that we used double underscores <code>__</code> to do a filtering on a field across Entities.</p>

<p>List of all employees which joined a given department this year.</p>

<pre><code>Employee.objects.filter(department = department, employment_history__date_joined__gte=start_of_year, )
</code></pre>

<p>Note that we used a double underscore <code>__</code> twice, first to go across entities, and then to define the type of filter(<code>__gte</code>).
Also we specified two filter conditions, so they were <code>ANDed</code> together.</p>

<p>List all employees which either report too a given employee, or joined before him.</p>

<pre><code>Employee.objects.filter(Q(manager = employee)|Q(employee_history__date_joined__lt = employee.employee_history.date_joined))
</code></pre>

<p>Note the new construct <code>Q</code>, they are used to specify complex boolean operations. Here we used the <code>|</code> (or operator) to specify or condition.</p>

<hr />

<p><a href="http://feeds.feedburner.com/uswarearticles">Do you subscribe to our rss feed</a>? The new feed has full text feed and many other goodness. So make sure you are subscribed to the new feed with extra fortified vitamins. <a href="http://feeds.feedburner.com/uswarearticles">Subscribe now</a>.</p>


<p>Related posts:<ol><li><a href='http://uswaretech.com/blog/2009/08/django-aggregation-tutorial/' rel='bookmark' title='Permanent Link: Django aggregation tutorial'>Django aggregation tutorial</a></li>
<li><a href='http://uswaretech.com/blog/2010/03/the-rails-and-django-models-layer-rosseta-stone/' rel='bookmark' title='Permanent Link: The Rails and Django models layer Rosseta stone'>The Rails and Django models layer Rosseta stone</a></li>
<li><a href='http://uswaretech.com/blog/2008/10/dynamic-forms-with-django/' rel='bookmark' title='Permanent Link: Dynamic forms with Django'>Dynamic forms with Django</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://uswaretech.com/blog/2010/01/django-models-tutorial/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Tools of Pro Django developer &#8211; aka What powers dinette and almost every app we write.</title>
		<link>http://uswaretech.com/blog/2010/01/tools-of-pro-django-developer/</link>
		<comments>http://uswaretech.com/blog/2010/01/tools-of-pro-django-developer/#comments</comments>
		<pubDate>Wed, 13 Jan 2010 12:32:11 +0000</pubDate>
		<dc:creator>shabda</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[django]]></category>

		<guid isPermaLink="false">http://uswaretech.com/blog/?p=870</guid>
		<description><![CDATA[There are some tools and apps which we use with almost all apps we write, and in particular which, we used for dinette. Here they are broken into useful during development, and (also) useful post development. During Development Ipython and ipdb South Django test utils Django extensions Django debug toolbar Ipython and ipdb Ipython is [...]


Related posts:<ol><li><a href='http://uswaretech.com/blog/2009/11/django-for-a-rails-developer/' rel='bookmark' title='Permanent Link: Django for a Rails Developer'>Django for a Rails Developer</a></li>
<li><a href='http://uswaretech.com/blog/2010/01/django-models-tutorial/' rel='bookmark' title='Permanent Link: Doing things with Django models &#8211; aka &#8211; Django models tutorial'>Doing things with Django models &#8211; aka &#8211; Django models tutorial</a></li>
<li><a href='http://uswaretech.com/blog/2009/02/how-to-build-a-facebook-app-in-django/' rel='bookmark' title='Permanent Link: How to build a Facebook app in Django'>How to build a Facebook app in Django</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p></p><p>There are some tools and apps which we use with almost all apps we write, and in particular which,
we used for <a href="http://uswaretech.com/forum/">dinette</a>. Here they are broken into useful during development,
and (also) useful post development.</p>

<h4>During Development</h4>

<ol>
<li><a href="http://ipython.scipy.org/">Ipython</a> and <a href="http://pypi.python.org/pypi/ipdb">ipdb</a></li>
<li><a href="http://south.aeracode.org/">South</a></li>
<li><a href="http://ericholscher.com/projects/django-test-utils/">Django test utils</a></li>
<li><a href="http://github.com/django-extensions/django-extensions">Django extensions</a></li>
<li><a href="http://github.com/robhudson/django-debug-toolbar">Django debug toolbar</a></li>
</ol>

<h5><a href="http://ipython.scipy.org/">Ipython</a> and <a href="http://pypi.python.org/pypi/ipdb">ipdb</a></h5>

<p>Ipython is a enhanced shell for python. Ipdb similarly add extra capacity to the builtin pdb debugger.
It is extremely convenient to drop into a ipython shell right where a complex piece of code is being hit.</p>

<pre><code>from IPython.Shell import IPShellEmbed
ipython = IPShellEmbed()
ipython()
</code></pre>

<p>Of course this does not allow you to step through, so if you want to step through your code, you need to do</p>

<pre><code>import ipdb
ipdb.set_trace()
</code></pre>

<p>Of course, you can just do <code>pdb.set_trace()</code>, but with tab completion and syntax highlighting, using ipdb is a no brainer.</p>

<h5><a href="http://south.aeracode.org/">South</a></h5>

<p>South adds schema migration to Django. It has lot of advanced options, but just three command will get you along way.</p>

<p>Convert a normal app to use the south way.</p>

<pre><code>./manage.py convert_to_south
</code></pre>

<p>Once you have made any changes to your apps model, write a new migration which can update the database to latest models.py</p>

<pre><code>./manage.py startmigration appname nameofmigration --auto
</code></pre>

<p>Once you have written a migration, write a command to update the db.</p>

<pre><code>./manage.py migrate appanme 
</code></pre>

<h5><a href="http://ericholscher.com/projects/django-test-utils/">Django test utils</a></h5>

<p>When you are running tests, a huge time sink is the time spent dropping and recreating tests. You might add just a single test,
and the default Django testrunner will spend a huge time recreating the database. Enter <code>manage.py quicktest</code> which reuses databases
between test runs. One of the side effects of this is that if you modify <code>models.py</code> between test runs you should manually
recreate the database.</p>

<p>The tests (or whatever little of it exists) for Dinette were written using testutils&#8217;
<a href="http://github.com/ericholscher/django-test-utils/tree/master/test_utils/testmaker/">testmaker</a>.</p>

<h5><a href="http://github.com/django-extensions/django-extensions">Django extensions</a></h5>

<p>Django extensions, (earlier Django command extensions) is a app which adds extra commands to <code>manage.py</code>. It has lot of goodies, but just
<code>./manage.py shell_plus</code> makes it worthwhile. (It imports all the models from all the apps automatically).</p>

<p>Get the full list at <a href="http://wiki.github.com/django-extensions/django-extensions/current-command-extensions">Github</a></p>

<h5><a href="http://github.com/robhudson/django-debug-toolbar">Django debug toolbar</a></h5>

<p>I do not personally use it but some people on our <a href="http://uswaretech.com/team/">team</a> swear by it.</p>

<h3>After development</h3>

<ol>
<li><a href="http://github.com/ericflo/django-pagination">Django-pagination</a></li>
<li><a href="http://thumbnail.sorl.net/docs/">sorl-thumbnails</a></li>
<li><a href="http://github.com/mintchaos/django_compressor/">django-compressor</a></li>
<li><a href="http://haystacksearch.org">Haystack</a></li>
</ol>

<h5><a href="http://github.com/ericflo/django-pagination">Django-pagination</a></h5>

<p>I have decided on a standard way to build apps which need pagination. a. Build apps without pagination. b. The night
before release spend an hour and add pagination to all pages. Really this is all you need</p>

<pre><code>{% load pagination tags %}
{% autopaginate queryset %}
....
{% paginate %}
</code></pre>

<p>There is no change required to the views.</p>

<h5><a href="http://thumbnail.sorl.net/docs/">sorl-thumbnails</a></h5>

<p>To thumbnail an image.</p>

<pre><code>{% thumbnail image size %}
</code></pre>

<p>&#8220;Things should be as simple as possible, but not simpler.&#8221;</p>

<h5><a href="http://github.com/mintchaos/django_compressor/">django-compressor</a></h5>

<p>During development we work with multiple unminified js and css files. Django-compressor takes care of minifying and compressing
it when we deploy. All we need to do is,</p>

<pre><code>{% compress css %}
...
all css files
....
{% endcompress %}


{% compress js %}
...
all js files
....
{% endcompress %}
</code></pre>

<h5><a href="http://haystacksearch.org">Haystack</a></h5>

<p>Haystack is &#8220;modular search for Django&#8221;. It make writing search views as easy as writing the admin. You declaratively tell what
fields you want to search on, and Haystack can take care of creating and updating the index, and providing a generic view
to handle the search. Check a search view written using Haystack <a href="http://uswaretech.com/forum/search/?q=django">http://uswaretech.com/forum/search/?q=django</a></p>

<hr />

<p>To everyone who contributed to these apps, thanks. Django development won&#8217;t be the same without these great tools.
This post was inspired by <a href="http://montylounge.com/">Kevin Fricovsky&#8217;s post</a> post, <a href="http://blog.montylounge.com/2009/sep/24/apps-that-power-django-mingus/">The apps that power Django-Mingus</a>
and is stolen about 50% from there. Thanks. <img src='http://uswaretech.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>

<hr />

<p>We build Amazing web apps, and we can build it for you. <a href="http://uswaretech.com/contact/">Contact us today</a>.</p>


<p>Related posts:<ol><li><a href='http://uswaretech.com/blog/2009/11/django-for-a-rails-developer/' rel='bookmark' title='Permanent Link: Django for a Rails Developer'>Django for a Rails Developer</a></li>
<li><a href='http://uswaretech.com/blog/2010/01/django-models-tutorial/' rel='bookmark' title='Permanent Link: Doing things with Django models &#8211; aka &#8211; Django models tutorial'>Doing things with Django models &#8211; aka &#8211; Django models tutorial</a></li>
<li><a href='http://uswaretech.com/blog/2009/02/how-to-build-a-facebook-app-in-django/' rel='bookmark' title='Permanent Link: How to build a Facebook app in Django'>How to build a Facebook app in Django</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://uswaretech.com/blog/2010/01/tools-of-pro-django-developer/feed/</wfw:commentRss>
		<slash:comments>23</slash:comments>
		</item>
		<item>
		<title>Python metaclasses and how Django uses them</title>
		<link>http://uswaretech.com/blog/2009/12/python-metaclasses-and-how-django-uses-them/</link>
		<comments>http://uswaretech.com/blog/2009/12/python-metaclasses-and-how-django-uses-them/#comments</comments>
		<pubDate>Thu, 03 Dec 2009 17:29:48 +0000</pubDate>
		<dc:creator>shabda</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[presentations]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://uswaretech.com/blog/?p=798</guid>
		<description><![CDATA[Foss.in is without doubt India&#8217;s largest FOSS technology conference. Lakshman gave a talk today on &#8220;Python metaclasses and how Django uses them&#8221;. Here are the slides from that talk. Doing magic with python metaclassesView more documents from Usware Technologies. [Edit] Some reactions, http://twitter.com/jaideep2588/status/6295483833 http://twitter.com/kunalbharati/status/6296572939 And the talk images, http://twitpic.com/rxhn7 You should follow us on twitter [...]


Related posts:<ol><li><a href='http://uswaretech.com/blog/2009/11/the-magic-of-metaclasses-in-python/' rel='bookmark' title='Permanent Link: The magic of metaclasses in Python'>The magic of metaclasses in Python</a></li>
<li><a href='http://uswaretech.com/blog/2009/09/python-tutorial-slides/' rel='bookmark' title='Permanent Link: Beginning python'>Beginning python</a></li>
<li><a href='http://uswaretech.com/blog/2009/06/better-python-package-management-using-source-and-version-control-systems/' rel='bookmark' title='Permanent Link: Better Python package management using source and version control systems'>Better Python package management using source and version control systems</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p></p><p><a href="http://foss.in/2009/">Foss.in</a> is without doubt India&#8217;s <a href="http://twitter.com/#search?q=fossdotin">largest</a> FOSS technology conference. <a href="http://foss.in/2009/schedules/talkdetailspub.php?talkid=44">Lakshman gave a talk</a> today on &#8220;Python metaclasses and how Django uses them&#8221;. Here are the slides from that talk.</p>

<div style="width:425px;text-align:left" id="__ss_2642704"><a style="font:14px Helvetica,Arial,Sans-serif;display:block;margin:12px 0 3px 0;text-decoration:underline;" href="http://www.slideshare.net/uswaretech/doing-magic-with-python-metaclasses" title="Doing magic with python metaclasses">Doing magic with python metaclasses</a><object style="margin:0px" width="425" height="355"><param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=foos-lakshman-091203110615-phpapp02&#038;stripped_title=doing-magic-with-python-metaclasses" /><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><embed src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=foos-lakshman-091203110615-phpapp02&#038;stripped_title=doing-magic-with-python-metaclasses" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"></embed></object><div style="font-size:11px;font-family:tahoma,arial;height:26px;padding-top:2px;">View more <a style="text-decoration:underline;" href="http://www.slideshare.net/">documents</a> from <a style="text-decoration:underline;" href="http://www.slideshare.net/uswaretech">Usware Technologies</a>.</div></div>

<hr />

<p>[Edit]
Some reactions,<br />
<a href="http://twitter.com/jaideep2588/status/6295483833">http://twitter.com/jaideep2588/status/6295483833</a><br />
<a href="http://twitter.com/kunalbharati/status/6296572939">http://twitter.com/kunalbharati/status/6296572939</a></p>

<p>And the talk images, <a href="http://twitpic.com/rxhn7">http://twitpic.com/rxhn7</a></p>

<hr />

<p><a href="http://twitter.com/uswaretech">You should follow us on twitter</a> and <a href="http://feeds.feedburner.com/uswarearticles">Subscribe to our blog</a></p>


<p>Related posts:<ol><li><a href='http://uswaretech.com/blog/2009/11/the-magic-of-metaclasses-in-python/' rel='bookmark' title='Permanent Link: The magic of metaclasses in Python'>The magic of metaclasses in Python</a></li>
<li><a href='http://uswaretech.com/blog/2009/09/python-tutorial-slides/' rel='bookmark' title='Permanent Link: Beginning python'>Beginning python</a></li>
<li><a href='http://uswaretech.com/blog/2009/06/better-python-package-management-using-source-and-version-control-systems/' rel='bookmark' title='Permanent Link: Better Python package management using source and version control systems'>Better Python package management using source and version control systems</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://uswaretech.com/blog/2009/12/python-metaclasses-and-how-django-uses-them/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Django for a Rails Developer</title>
		<link>http://uswaretech.com/blog/2009/11/django-for-a-rails-developer/</link>
		<comments>http://uswaretech.com/blog/2009/11/django-for-a-rails-developer/#comments</comments>
		<pubDate>Thu, 26 Nov 2009 13:42:21 +0000</pubDate>
		<dc:creator>Ashok</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[django ruby rails]]></category>

		<guid isPermaLink="false">http://uswaretech.com/blog/?p=751</guid>
		<description><![CDATA[This is not yet another Django vs Rails blog post. It is a compilation of notes I made working with Django after having worked on Rails for years. In this post I want to give a brief introduction to Django project layout from a Rails developer point of view, on what is there, what is [...]


Related posts:<ol><li><a href='http://uswaretech.com/blog/2010/03/rails-and-django-commands-comparison-and-conversion/' rel='bookmark' title='Permanent Link: Rails and Django commands : comparison  and conversion'>Rails and Django commands : comparison  and conversion</a></li>
<li><a href='http://uswaretech.com/blog/2010/03/the-rails-and-django-models-layer-rosseta-stone/' rel='bookmark' title='Permanent Link: The Rails and Django models layer Rosseta stone'>The Rails and Django models layer Rosseta stone</a></li>
<li><a href='http://uswaretech.com/blog/2010/01/tools-of-pro-django-developer/' rel='bookmark' title='Permanent Link: Tools of Pro Django developer &#8211; aka What powers dinette and almost every app we write.'>Tools of Pro Django developer &#8211; aka What powers dinette and almost every app we write.</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p></p><p>This is not yet another <a href="http://www.djangoproject.com/">Django</a> vs <a href="http://rubyonrails.org/">Rails</a> blog post. It is a compilation of notes I made working with Django after having worked on Rails for years.</p>

<p>In this post I want to give a brief introduction to Django project layout from a Rails developer point of view, on what is there, what is not there and where to look for things. It should help a rails developer working on django be able to find the necessary files and underatnd the layout of the project files.</p>

<p>Once you have both the frameworks installed on your system you can create the projects using the commands</p>

<pre><code># creating a rails project
rails rails_project
# creating a Django project
django-admin.py startproject django_project
</code></pre>

<p>Lets look at the files and structure created by the respective frameworks</p>

<pre><code>#rails_project
README
Rakefile
app/
    controllers/
        application_controller.rb
    helpers/
        application_helper.rb
    models/
    views/
        layouts/
config/
    boot.rb
    database.yml
    environment.rb
    environments/
        development.rb
        production.rb
        test.rb
    initializers/
        backtrace_silencers.rb
        inflections.rb
        mime_types.rb
        new_rails_defaults.rb
        session_store.rb
    locales/
        en.yml
    routes.rb
db/
    seeds.rb
doc/
    README_FOR_APP
lib/
    tasks/
log/
    development.log
    production.log
    server.log
    test.log
public/
    404.html
    422.html
    500.html
    favicon.ico
    images/
        rails.png
    index.html
    javascripts/
        application.js
        controls.js
        dragdrop.js
        effects.js
        prototype.js
    robots.txt
    stylesheets/
script/
    about
    console
    dbconsole
    destroy
    generate
    performance/
        benchmarker
        profiler
    plugin
    runner
    server
test/
    fixtures/
    functional/
    integration/
    performance/
        browsing_test.rb
    test_helper.rb
    unit/
tmp/
    cache/
    pids/
    sessions/
    sockets/
vendor/
    plugins/
</code></pre>

<p>that is huge&#8230;.</p>

<p>lets look at the django project files</p>

<pre><code># django_project
__init__.py
manage.py
settings.py
urls.py
</code></pre>

<p>far lesser when compared to the rails project.</p>

<p>In fact a rails project comes with everything a web application needs. When I say everything I mean everything&#8230;.. base application, routing, database configuration, development, test and production environment specific configurations and their respective log files,  javascript, test, some standard html files and some helpful scripts for developing.</p>

<p>Why then does a Django project have so less number of files? It has got to do with the Django&#8217;s philosophy and the concept of applications. The django project is not complete without the application, so lets create a application inside the project and have a look at the structure</p>

<pre><code>django-admin.py startapp app

# django_project
__init__.py
app/
    __init__.py
    models.py
    tests.py
    views.py
manage.py
settings.py
urls.py
</code></pre>

<p>even after including this, the number of files is still less than the rails project.</p>

<p>Lets break it down and relate both the frameworks.</p>

<table width='100%' border='1px'>
    <thead>
        <tr>
            <th></th>
            <th>Rails</th>
            <th>Django</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td width='20%'>Configuration Files</td>
            <td width='40%'>
                <li>config/database.yml for database settings</li>
                config/environments/
                <li>development.rb for development specific settings</li>
                <li>production.rb for production specific settings</li>
                <li>test.rb for test specific settings</li>
            </td>
            <td width='40%'>
                settings.py, one file for everything, database configuration and any other configuaration or settings will be in this file
            </td>
        </tr>
        <tr>
            <td>URLs</td>
            <td>
                config/routes.rb
            </td>
            <td>
                urls.py
            </td>
        </tr>
        <tr>
            <td>Schema/Models</td>
            <td>
                <li>db/schema.rb for the ruby version of db schema</li>
                <li>app/models/* for the models</li>
            </td>
            <td>
                <li>complete schema is not stored any where</li>
                <li>Under every application in your project, models.py file will contain the table specific schema stored as django models</li>
            </td>
        </tr>
        <tr>
            <td>Management Commands</td>
            <td>
                <li>./script/server,  start server</li>
                <li>./script/console, ruby console</li>
                <li>./script/dbconsole, database console</li>
                <li>rake db:migrate, run database migrations</li>
            </td>
            <td>
                manage.py is the file for all your tasks
                <li>./manage.py runserver, start server</li>
                <li>./manage.py shell, python console</li>
                <li>./manage.py dbshell, database console</li>
                <li>./manage.py syncdb</li>
            </td>
        </tr>
        <tr>
            <td>Application Code</td>
            <td>
                app/controllers/* will contain the application logic
            </td>
            <td>
                views.py file under each application folder is the place to write to your application logic, file can be named with any name, views.py is the general convention
            </td>
        </tr>
        <tr>
            <td>Application templates</td>
            <td>
                app/views/<controller_name>/* is the place for the templates
            </td>
            <td>
                <li> default: looks inside &#8216;templates&#8217; directory, under the application directory</li>
                <li> looks in the directory specified by &#8216;TEMPLATE_DIRS&#8217; in settings.py </li>
            </td>
        </tr>

    </tbody>
</table>

<p>and lets have a look at the other things in rails_project</p>

<ul>
        <li>Logging, unders the logs directory </li>
        <li>Some default html files for some standard http errors, under the public directory </li>
        <li>Rails has very good support for testing, for that bunch of files under tests </li>
        <li>Vendor/Plugin, place for some third party plugins/applications. </li>
    </ul>

<p>Missing pieces in Django (for a rails developer)</p>

<ul>
        <li>Scaffold magic</li>
        <li>Generate commands</li>
        <li>Migrations</li>
    </ul>

<p>and what is Django is providing by default? Sorry no extra files in the project; but you will get an authentication system and Django&#8217;s killer feature, admin, just by modifying your &#8216;INSTALLED_APPS&#8217; in your settings. It is similar to the plugins feature in Rails, Django&#8217;s philosophy of resusable apps helps you in getting any particular functionality into your project.</p>

<p>Following is a list of what I like in Django (and associated apps):
<li>Admin (almost everybodys favourite)</li>
<li>Generic Views, helps from writing a lot of repetetive code, <a href='http://www.b-list.org/weblog/2006/nov/16/django-tips-get-most-out-generic-views/'>James Bennett&#8217;s blog on generic views</a></li>
<li>Django DB API &amp; QuerySets, (chaining and the filters that are missing in ActiveRecord)</li>
<li>Forms and above all, my favorite yet: <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/">ModelForm</a>.</li>
<li>You can get the migrations feature in Django using <a href="http://south.aeracode.org/">South</a>. Being an external app, it a bit of pain in setting it up to work with South. Other than that it is more like rails migrations</li>
<li><a href="http://code.google.com/p/django-command-extensions/">django-command-extensions</a></li>
<li><a href="http://haystacksearch.org/">Search the Django way</a></li></p>

<p>Following are the questions that I keep getting, 
 <li>When a project will almost have a application why creating project &amp; app has to be two different steps?</li>
<li>Why not create a &#8216;templates&#8217; directoy and a &#8216;base.html&#8217; either in project&#8217;s directory or in the apps&#8217;s directory, because creating the same templates directory and same base.html for every project is not DRY <img src='http://uswaretech.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  ?</li>
<li> Why serving static files in development has to be a additional setup, as no developer wants to setup a server for serving static files, I am aware of &#8216;django.static.serve&#8217; but still that is an additional setup, why not create a sample media directory and a url for the same in urls.py ?</li></p>

<p>let me know via comments, if you have any answers</p>

<p>program used for listing the files in a directory</p>

<pre><code>import os
import sys

try:
    directory = sys.argv[1]
except IndexError:
    directory = os.path.dirname(os.path.abspath(__file__))

def r_list_dir(directory, indent=0):
    dir_files = sorted([os.path.join(directory, file_name) for file_name in  os.listdir(directory)])
    for item in dir_files:
        if os.path.isdir(item):
            print " " * indent + os.path.split(item)[1] + '/'
            r_list_dir(item, indent+4)
        else:
            print " " * indent + os.path.split(item)[1]

r_list_dir(directory)
</code></pre>


<p>Related posts:<ol><li><a href='http://uswaretech.com/blog/2010/03/rails-and-django-commands-comparison-and-conversion/' rel='bookmark' title='Permanent Link: Rails and Django commands : comparison  and conversion'>Rails and Django commands : comparison  and conversion</a></li>
<li><a href='http://uswaretech.com/blog/2010/03/the-rails-and-django-models-layer-rosseta-stone/' rel='bookmark' title='Permanent Link: The Rails and Django models layer Rosseta stone'>The Rails and Django models layer Rosseta stone</a></li>
<li><a href='http://uswaretech.com/blog/2010/01/tools-of-pro-django-developer/' rel='bookmark' title='Permanent Link: Tools of Pro Django developer &#8211; aka What powers dinette and almost every app we write.'>Tools of Pro Django developer &#8211; aka What powers dinette and almost every app we write.</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://uswaretech.com/blog/2009/11/django-for-a-rails-developer/feed/</wfw:commentRss>
		<slash:comments>99</slash:comments>
		</item>
		<item>
		<title>Writing your own template loaders</title>
		<link>http://uswaretech.com/blog/2009/11/writing-your-own-template-loaders/</link>
		<comments>http://uswaretech.com/blog/2009/11/writing-your-own-template-loaders/#comments</comments>
		<pubDate>Sat, 21 Nov 2009 10:41:17 +0000</pubDate>
		<dc:creator>shabda</dc:creator>
				<category><![CDATA[django]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://uswaretech.com/blog/?p=733</guid>
		<description><![CDATA[Django has three builtin template loaders which are used to get the templates for rendering. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', # 'django.template.loaders.eggs.load_template_source', ) Writing your template loader is a awfuly easy. It is a callable which Returns a tuple of (openfile, filename) if it can find the template. Raise TemplateDoesNotExist if the templates cannot be [...]


Related posts:<ol><li><a href='http://uswaretech.com/blog/2009/08/a-response-to-dropping-django/' rel='bookmark' title='Permanent Link: A response to Dropping Django'>A response to Dropping Django</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p></p><p>Django has three builtin template loaders which are used to get the templates for rendering.</p>

<pre><code>TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.load_template_source',
    'django.template.loaders.app_directories.load_template_source',
#     'django.template.loaders.eggs.load_template_source',
)
</code></pre>

<p>Writing your template loader is a awfuly easy. It is a callable which</p>

<ol>
<li>Returns a tuple of (openfile, filename) if it can find the template.</li>
<li>Raise TemplateDoesNotExist if the templates cannot be found.</li>
</ol>

<p>The simplest template loader can be</p>

<pre><code>from django.template import TemplateDoesNotExist
def load_template_source(template_name, template_dirs=None):
        try:
            return open(template_name).read(), template_name
        except IOError:
            raise TemplateDoesNotExist, template_name
</code></pre>

<p>if you put this to your template loaders directory,</p>

<pre><code>TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.load_template_source',
    'django.template.loaders.app_directories.load_template_source',
    'dgrid.load_template_source'
#     'django.template.loaders.eggs.load_template_source',
</code></pre>

<p>You can do access a template using an absolute path.</p>

<pre><code>In [6]: get_template('/home/shabda/abc.txt')
Out[6]: &lt;django.template.Template object at 0x91c860c&gt;

In [7]: temp = get_template('/home/shabda/abc.txt')

In [8]: temp
Out[8]: &lt;django.template.Template object at 0x9358a0c&gt;

In [9]: temp.render
Out[9]: &lt;bound method Template.render of &lt;django.template.Template object at 0x9358a0c&gt;&gt;
</code></pre>

<hr />

<p>This is the first in the series of <code>short and sweet</code> Django posts we are going to do. You are interested, right. Do follow us on <a href="http://twitter.com/uswaretech">twitter</a> or <a href="http://feeds.feedburner.com/uswarearticles">subscribe to our feed</a>.</p>

<hr />

<p>We build <em>Amazing We Apps</em>. <a href="http://uswaretech.com/contact/">Talk to us</a> or email us at sales@uswaretech.com .</p>


<p>Related posts:<ol><li><a href='http://uswaretech.com/blog/2009/08/a-response-to-dropping-django/' rel='bookmark' title='Permanent Link: A response to Dropping Django'>A response to Dropping Django</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://uswaretech.com/blog/2009/11/writing-your-own-template-loaders/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Beginning python</title>
		<link>http://uswaretech.com/blog/2009/09/python-tutorial-slides/</link>
		<comments>http://uswaretech.com/blog/2009/09/python-tutorial-slides/#comments</comments>
		<pubDate>Fri, 18 Sep 2009 11:46:43 +0000</pubDate>
		<dc:creator>shabda</dc:creator>
				<category><![CDATA[presentations]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://uswaretech.com/blog/?p=682</guid>
		<description><![CDATA[Slides and code from my talk at twincling. Beginning PythonView more documents from Usware Technologies. Talk CodeView more documents from Usware Technologies. Related posts:Python metaclasses and how Django uses them Python Wrapper on Bing API Better Python package management using source and version control systems


Related posts:<ol><li><a href='http://uswaretech.com/blog/2009/12/python-metaclasses-and-how-django-uses-them/' rel='bookmark' title='Permanent Link: Python metaclasses and how Django uses them'>Python metaclasses and how Django uses them</a></li>
<li><a href='http://uswaretech.com/blog/2009/06/bing-python-api/' rel='bookmark' title='Permanent Link: Python Wrapper on Bing API'>Python Wrapper on Bing API</a></li>
<li><a href='http://uswaretech.com/blog/2009/06/better-python-package-management-using-source-and-version-control-systems/' rel='bookmark' title='Permanent Link: Better Python package management using source and version control systems'>Better Python package management using source and version control systems</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p></p><p><a href="http://www.slideshare.net/uswaretech/beginning-python">Slides</a> and <a href="http://bit.ly/pytalk">code</a> from my talk at <a href="http://twincling.org/node/725">twincling</a>.</p>

<div style="width:425px;text-align:left" id="__ss_1991104"><a style="font:14px Helvetica,Arial,Sans-serif;display:block;margin:12px 0 3px 0;text-decoration:underline;" href="http://www.slideshare.net/uswaretech/beginning-python" title="Beginning Python">Beginning Python</a><object style="margin:0px" width="425" height="355"><param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=talk-090913073858-phpapp02&#038;stripped_title=beginning-python" /><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><embed src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=talk-090913073858-phpapp02&#038;stripped_title=beginning-python" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"></embed></object><div style="font-size:11px;font-family:tahoma,arial;height:26px;padding-top:2px;">View more <a style="text-decoration:underline;" href="http://www.slideshare.net/">documents</a> from <a style="text-decoration:underline;" href="http://www.slideshare.net/uswaretech">Usware Technologies</a>.</div></div>

<div style="width:477px;text-align:left" id="__ss_1995742"><a style="font:14px Helvetica,Arial,Sans-serif;display:block;margin:12px 0 3px 0;text-decoration:underline;" href="http://www.slideshare.net/uswaretech/talk-code" title="Talk Code">Talk Code</a><object style="margin:0px" width="477" height="510"><param name="movie" value="http://static.slidesharecdn.com/swf/ssplayerd.swf?doc=talkcode-090914105528-phpapp01&#038;stripped_title=talk-code" /><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><embed src="http://static.slidesharecdn.com/swf/ssplayerd.swf?doc=talkcode-090914105528-phpapp01&#038;stripped_title=talk-code" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="477" height="510"></embed></object><div style="font-size:11px;font-family:tahoma,arial;height:26px;padding-top:2px;">View more <a style="text-decoration:underline;" href="http://www.slideshare.net/">documents</a> from <a style="text-decoration:underline;" href="http://www.slideshare.net/uswaretech">Usware Technologies</a>.</div></div>


<p>Related posts:<ol><li><a href='http://uswaretech.com/blog/2009/12/python-metaclasses-and-how-django-uses-them/' rel='bookmark' title='Permanent Link: Python metaclasses and how Django uses them'>Python metaclasses and how Django uses them</a></li>
<li><a href='http://uswaretech.com/blog/2009/06/bing-python-api/' rel='bookmark' title='Permanent Link: Python Wrapper on Bing API'>Python Wrapper on Bing API</a></li>
<li><a href='http://uswaretech.com/blog/2009/06/better-python-package-management-using-source-and-version-control-systems/' rel='bookmark' title='Permanent Link: Better Python package management using source and version control systems'>Better Python package management using source and version control systems</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://uswaretech.com/blog/2009/09/python-tutorial-slides/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Fun with none</title>
		<link>http://uswaretech.com/blog/2009/07/fun-with-none/</link>
		<comments>http://uswaretech.com/blog/2009/07/fun-with-none/#comments</comments>
		<pubDate>Thu, 16 Jul 2009 07:07:45 +0000</pubDate>
		<dc:creator>rohit</dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[ideas]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://uswaretech.com/blog/?p=617</guid>
		<description><![CDATA[(If you are in a hurry, here is the fun part. A few days ago, I was working with a nullable field, which wasn&#8217;t behaving as I expected. So I started a shell, and see how nulls compare. In [1]: None In [2]: None &#62; 10 Out[2]: False In [3]: None &#60; 10 Out[3]: True [...]


Related posts:<ol><li><a href='http://uswaretech.com/blog/2010/03/the-rails-and-django-models-layer-rosseta-stone/' rel='bookmark' title='Permanent Link: The Rails and Django models layer Rosseta stone'>The Rails and Django models layer Rosseta stone</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p></p><p>(If you are in a hurry, <a href="#funn">here is the fun part.</a> <img src='http://uswaretech.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>

<p>A few days ago, I was working with a nullable field, which wasn&#8217;t behaving as I expected. So I started a shell, and see how nulls compare.
<pre></p>

<div class="line">In [1]: None</div>

<div class="line">In [2]: None &gt; 10</div>

<div class="line">Out[2]: False</div>

<div class="line">In [3]: None &lt; 10</div>

<div class="line">Out[3]: True</div>

<div class="line">In [4]: None == None</div>

<div class="line">Out[4]: True</div>

<p></pre>
Funny, not as I expected. (Why is None &lt; 10 True. I thought it would be either False or None or cause an Error?)</p>

<p>So python is obviously broken, next steps, see the same thing in some other language. Lets try some other language, Javascript maybe?</p>

<div class="highlight">
<pre>
<div class="line">//#Javascript</div>
<div class="line">&gt;&gt;&gt; null</div>
<div class="line">null</div>
<div class="line">&gt;&gt;&gt; null == 10</div>
<div class="line">false</div>
<div class="line">&gt;&gt;&gt; null &gt; 10</div>
<div class="line">false</div>
<div class="line">&gt;&gt;&gt; null &lt; 10</div>
<div class="line">true</div>
<div class="line">&gt;&gt;&gt; null == null</div>
<div class="line">true</div></pre>
</div>

<p>Ruby?
<pre>irb(main):001:0&gt; nil
=&gt; nil
irb(main):002:0&gt; nil &gt; 10
NoMethodError: undefined method <code>&amp;gt;' for nil:NilClass
  from (irb):2
  from :0
irb(main):003:0&amp;gt; 10 &amp;gt; nil
ArgumentError: comparison of Fixnum with nil failed
  from (irb):3:in</code>&gt;'
  from (irb):3
  from :0
irb(main):004:0&gt; 10 &lt; nil
ArgumentError: comparison of Fixnum with nil failed
  from (irb):4:in ` 10 == nil
=&gt; false</pre>
So, this piqued my curiosity and without further ado, here is how None/nil/null/Nothing behave in fifteen different languages. You would assume they would have sorted something this basic out by now. <img src='http://uswaretech.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>

<p><a name="funn"></a></p>

<h3>Comparision of how null behaves in different languages for</h3>

<ul>
    <li>null &gt; 10</li>
    <li>null &lt; 10</li>
    <li>null == 10</li>
    <li>null == null</li>
</ul>

<table class="ta1" border="1" cellspacing="0" cellpadding="0"><col></col><col></col><col></col><col></col><col></col><col></col><col></col><col></col>
<tbody>
<tr class="ro1">
<td class="Default" style="2.267cm;"></td>
<td class="ce1" style="2.267cm;">Null &gt; 10</td>
<td class="ce1" style="2.267cm;">Null &lt; 10</td>
<td class="ce1" style="2.267cm;">Null == null</td>
<td class="ce1" style="2.267cm;">10 == 10</td>
<td class="ce1" style="2.267cm;">Null == 10</td>
<td class="ce1" style="2.267cm;">names</td>
<td class="ce1" style="6.724cm;">Link</td>
</tr>
<tr class="ro1">
<td class="ce1" style="2.267cm;">Python</td>
<td class="ce2" style="2.267cm;">FALSE</td>
<td class="ce2" style="2.267cm;">TRUE</td>
<td class="ce2" style="2.267cm;">TRUE</td>
<td class="ce2" style="2.267cm;">TRUE</td>
<td class="ce2" style="2.267cm;">FALSE</td>
<td class="Default" style="2.267cm;">None</td>
<td class="Default" style="6.724cm;"><a rel="nofollow" href="http://gist.github.com/147892">http://gist.github.com/147892</a></td>
</tr>
<tr class="ro1">
<td class="ce1" style="2.267cm;">Ruby</td>
<td class="Default" style="2.267cm;">Error</td>
<td class="Default" style="2.267cm;">Error</td>
<td class="ce2" style="2.267cm;">TRUE</td>
<td class="ce2" style="2.267cm;">TRUE</td>
<td class="ce2" style="2.267cm;">FALSE</td>
<td class="Default" style="2.267cm;">nil</td>
<td class="Default" style="6.724cm;"><a rel="nofollow" href="http://gist.github.com/147894">http://gist.github.com/147894</a></td>
</tr>
<tr class="ro1">
<td class="ce1" style="2.267cm;">Lua</td>
<td class="Default" style="2.267cm;">Error</td>
<td class="Default" style="2.267cm;">Error</td>
<td class="ce2" style="2.267cm;">TRUE</td>
<td class="ce2" style="2.267cm;">TRUE</td>
<td class="ce2" style="2.267cm;">FALSE</td>
<td class="Default" style="2.267cm;">nil</td>
<td class="Default" style="6.724cm;"><a rel="nofollow" href="http://gist.github.com/147906">http://gist.github.com/147906</a></td>
</tr>
<tr class="ro1">
<td class="ce1" style="2.267cm;">Javascript</td>
<td class="ce2" style="2.267cm;">FALSE</td>
<td class="ce2" style="2.267cm;">TRUE</td>
<td class="ce2" style="2.267cm;">TRUE</td>
<td class="ce2" style="2.267cm;">TRUE</td>
<td class="ce2" style="2.267cm;">FALSE</td>
<td class="Default" style="2.267cm;">null</td>
<td class="Default" style="6.724cm;"><a rel="nofollow" href="http://gist.github.com/147909">http://gist.github.com/147909</a></td>
</tr>
<tr class="ro1">
<td class="ce1" style="2.267cm;">Mysql</td>
<td class="Default" style="2.267cm;">null</td>
<td class="Default" style="2.267cm;">null</td>
<td class="Default" style="2.267cm;">null</td>
<td class="ce2" style="2.267cm;">TRUE</td>
<td class="Default" style="2.267cm;">null</td>
<td class="Default" style="2.267cm;">null</td>
<td class="Default" style="6.724cm;"><a rel="nofollow" href="http://gist.github.com/147921">http://gist.github.com/147921</a></td>
</tr>
<tr class="ro1">
<td class="ce1" style="2.267cm;">Psql</td>
<td class="Default" style="2.267cm;">null</td>
<td class="Default" style="2.267cm;">null</td>
<td class="Default" style="2.267cm;">null</td>
<td class="ce2" style="2.267cm;">TRUE</td>
<td class="Default" style="2.267cm;">null</td>
<td class="Default" style="2.267cm;">null</td>
<td class="Default" style="6.724cm;"><a rel="nofollow" href="http://gist.github.com/147915">http://gist.github.com/147915</a></td>
</tr>
<tr class="ro1">
<td class="ce1" style="2.267cm;">Sqlite</td>
<td class="Default" style="2.267cm;">null</td>
<td class="Default" style="2.267cm;">null</td>
<td class="Default" style="2.267cm;">null</td>
<td class="ce2" style="2.267cm;">TRUE</td>
<td class="Default" style="2.267cm;">null</td>
<td class="Default" style="2.267cm;">null</td>
<td class="Default" style="6.724cm;"><a rel="nofollow" href="http://gist.github.com/147919">http://gist.github.com/147919</a></td>
</tr>
<tr class="ro1">
<td class="ce1" style="2.267cm;">Haskell</td>
<td class="Default" style="2.267cm;">Error</td>
<td class="Default" style="2.267cm;">Error</td>
<td class="ce2" style="2.267cm;">TRUE</td>
<td class="ce2" style="2.267cm;">TRUE</td>
<td class="Default" style="2.267cm;">Error</td>
<td class="Default" style="2.267cm;">Nothing</td>
<td class="Default" style="6.724cm;"><a rel="nofollow" href="http://gist.github.com/147953">http://gist.github.com/147953</a></td>
</tr>
<tr class="ro1">
<td class="ce1" style="2.267cm;">Clojure</td>
<td class="Default" style="2.267cm;">Error</td>
<td class="Default" style="2.267cm;">Error</td>
<td class="Default" style="2.267cm;">Error</td>
<td class="ce2" style="2.267cm;">TRUE</td>
<td class="Default" style="2.267cm;">Error</td>
<td class="Default" style="2.267cm;">nil</td>
<td class="Default" style="6.724cm;"><a rel="nofollow" href="http://gist.github.com/147958">http://gist.github.com/147958</a></td>
</tr>
<tr class="ro1">
<td class="ce1" style="2.267cm;">Java</td>
<td class="Default" style="2.267cm;">Error</td>
<td class="Default" style="2.267cm;">Error</td>
<td class="ce2" style="2.267cm;">TRUE</td>
<td class="ce2" style="2.267cm;">TRUE</td>
<td class="Default" style="2.267cm;">Error</td>
<td class="Default" style="2.267cm;">null</td>
<td class="Default" style="6.724cm;"><a rel="nofollow" href="http://gist.github.com/147932">http://gist.github.com/147932</a></td>
</tr>
<tr class="ro1">
<td class="ce1" style="2.267cm;">Groovy</td>
<td class="ce2" style="2.267cm;">FALSE</td>
<td class="ce2" style="2.267cm;">TRUE</td>
<td class="ce2" style="2.267cm;">TRUE</td>
<td class="ce2" style="2.267cm;">TRUE</td>
<td class="ce2" style="2.267cm;">FALSE</td>
<td class="Default" style="2.267cm;">null</td>
<td class="Default" style="6.724cm;"><a rel="nofollow" href="http://gist.github.com/147936">http://gist.github.com/147936</a></td>
</tr>
<tr class="ro1">
<td class="ce1" style="2.267cm;">Perl</td>
<td class="Default" style="2.267cm;">Error</td>
<td class="Default" style="2.267cm;">Error</td>
<td class="Default" style="2.267cm;">Error</td>
<td class="ce2" style="2.267cm;">TRUE</td>
<td class="Default" style="2.267cm;">Error</td>
<td class="Default" style="2.267cm;">undef</td>
<td class="Default" style="6.724cm;"><a rel="nofollow" href="http://gist.github.com/147925">http://gist.github.com/147925</a></td>
</tr>
<tr class="ro1">
<td class="ce1" style="2.267cm;">Scala</td>
<td class="Default" style="2.267cm;">Error</td>
<td class="Default" style="2.267cm;">Error</td>
<td class="ce2" style="2.267cm;">TRUE</td>
<td class="ce2" style="2.267cm;">TRUE</td>
<td class="ce2" style="2.267cm;">FALSE</td>
<td class="Default" style="2.267cm;">null</td>
<td class="Default" style="6.724cm;"><a rel="nofollow" href="http://gist.github.com/147923">http://gist.github.com/147923</a></td>
</tr>
<tr class="ro1">
<td class="ce1" style="2.267cm;">Jython</td>
<td class="ce2" style="2.267cm;">FALSE</td>
<td class="ce2" style="2.267cm;">TRUE</td>
<td class="ce2" style="2.267cm;">TRUE</td>
<td class="ce2" style="2.267cm;">TRUE</td>
<td class="ce2" style="2.267cm;">FALSE</td>
<td class="Default" style="2.267cm;">None</td>
<td class="Default" style="6.724cm;"><a rel="nofollow" href="http://gist.github.com/147914">http://gist.github.com/147914</a></td>
</tr>
<tr class="ro1">
<td class="ce1" style="2.267cm;">Php</td>
<td class="Default" style="2.267cm;">null</td>
<td class="ce2" style="2.267cm;">TRUE</td>
<td class="ce2" style="2.267cm;">TRUE</td>
<td class="ce2" style="2.267cm;">TRUE</td>
<td class="Default" style="2.267cm;">null</td>
<td class="Default" style="2.267cm;">null</td>
<td class="Default" style="6.724cm;"><a rel="nofollow" href="http://gist.github.com/147899">http://gist.github.com/147899</a></td>
</tr>
</tbody></table>

<p>All these are high level languages, and with exception of Java/Haskell/Sql are dynamically typed, so why is there this much difference in how None/null/nil as a type is handled?</p>

<hr />

<p>As you can tell, I am very new to some of these languages, so if I have got your favorite language wrong. Please let me know in the comments and I will fix it.</p>


<p>Related posts:<ol><li><a href='http://uswaretech.com/blog/2010/03/the-rails-and-django-models-layer-rosseta-stone/' rel='bookmark' title='Permanent Link: The Rails and Django models layer Rosseta stone'>The Rails and Django models layer Rosseta stone</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://uswaretech.com/blog/2009/07/fun-with-none/feed/</wfw:commentRss>
		<slash:comments>68</slash:comments>
		</item>
		<item>
		<title>Better Python package management using source and version control systems</title>
		<link>http://uswaretech.com/blog/2009/06/better-python-package-management-using-source-and-version-control-systems/</link>
		<comments>http://uswaretech.com/blog/2009/06/better-python-package-management-using-source-and-version-control-systems/#comments</comments>
		<pubDate>Wed, 24 Jun 2009 16:46:13 +0000</pubDate>
		<dc:creator>lakshman</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[easy_install]]></category>
		<category><![CDATA[pip]]></category>

		<guid isPermaLink="false">http://uswaretech.com/blog/?p=565</guid>
		<description><![CDATA[Thanks to awesome django community, there is plenty of open source django code around. These packages get updated quite often and if you use it often like we do, you&#8217;d have possibly realized the need to manage these packages better. Thankfully, all python ever needs is the source, and all you need to do is [...]


Related posts:<ol><li><a href='http://uswaretech.com/blog/2009/12/python-metaclasses-and-how-django-uses-them/' rel='bookmark' title='Permanent Link: Python metaclasses and how Django uses them'>Python metaclasses and how Django uses them</a></li>
<li><a href='http://uswaretech.com/blog/2009/06/bing-python-api/' rel='bookmark' title='Permanent Link: Python Wrapper on Bing API'>Python Wrapper on Bing API</a></li>
<li><a href='http://uswaretech.com/blog/2009/09/python-tutorial-slides/' rel='bookmark' title='Permanent Link: Beginning python'>Beginning python</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p></p><p>Thanks to awesome <a href="http://www.djangoproject.com/community/">django community</a>, there is plenty of open source <a href="http://code.google.com/hosting/search?q=django&amp;projectsearch=Search+projects">django</a> <a href="http://bitbucket.org/repo/all/?name=django">code</a> <a href="http://github.com/search?q=django&amp;type=Everything&amp;repo=&amp;langOverride=&amp;start_value=1">around</a>.</p>

<p>These packages get updated quite often and if you use it often like we do, you&#8217;d have possibly realized the need to manage these packages better.</p>

<p>Thankfully, all python ever needs is the source, and all you need to do is to place the source in the python path.</p>

<p>Most projects use Distributed Version Control Systems like Mercurial and Git, and they come locally with the entire history of the source which provides a lot of control to use any version of the code. For code that we use often, like django packages, using the source from a version control system seems to be the best way to manage.</p>

<p>In order to install <a href="http://bitbucket.org/ubernostrum/django-registration/">django-registration</a>, a popular django app by <a href="http://www.b-list.org/">James Bennett</a>, you need to:</p>

<p>Clone the repository:</p>

<pre><code>$ hg clone https://becomingguru@bitbucket.org/ubernostrum/django-registration/ django_registration
</code></pre>

<p>Create a symbolic link in the python path:</p>

<pre><code>$ sudo ln -fs ~/django_registration/registration /usr/lib/python2.6/dist-packages/django_registration
</code></pre>

<p>Thats it. <code>django_registration</code> is now on the python path, courtesy of symbollic link, that links the django-registration source to python path, in this case the <code>dist-packages/</code> folder; thus it will be possible to import this app within the python environment.</p>

<p>You now have the latest version of the source in the folder <code>~/django_registration</code>, which you can check, and modify. With an editor/IDE that has <em>go to source</em> option, you can browse the source by using a simple short cut.(which may not have been simple if the code were is some egg file in a less well known folder)</p>

<p>Because of cloning of the mercurial repository, you now have access to all the revisions of the application. So you can easily update, or change to other versions.</p>

<p>To update to a newer version when one exists:</p>

<pre><code>$ hg pull -u
</code></pre>

<p>To move to any particular revision:</p>

<pre><code>$ hg update -r200
</code></pre>

<p>To check the tags:</p>

<pre><code>$ hg tags

tip                              221:b360801eae96
v0.7                             205:d073602dc103
v0.6                             154:e263c551ef7b
v0.5                             139:dc2bf754aa94
v0.4                             110:4d2a725d8c18
v0.3                              75:f41e8a239016
v0.2                              58:e5110bb8d48a
v0.1                              42:d28e5a770ff8
</code></pre>

<p>If you want to update to a recent release, say 0.7,</p>

<pre><code> $  hg update v0.7
7 files updated, 0 files merged, 0 files removed, 0 files unresolved
</code></pre>

<p>The same is also applicable while dealing with SVN repositories; alebit some of the revision changes go thro the network to the central server.</p>

<p>In order to install and work with <a href="http://code.djangoproject.com/svn/django/trunk/">django trunk</a>, check out the trunk and add a symlink, as before</p>

<pre><code>$ svn co http://code.djangoproject.com/svn/django/trunk/ django-trunk
$ cd django-trunk/django
$ sudo ln -fs . /usr/lib/python2.6/dist-packages/django-extensions
</code></pre>

<p>You will now be able to access the latest version of django:</p>

<pre><code>$ python
&gt;&gt;&gt; import django
&gt;&gt;&gt; django.get_version()
u'1.1 beta 1 SVN-11092'
</code></pre>

<p>To use any other version of django you can do some SVN manipulation, as following:</p>

<pre><code>#To update to a latest version
svn up
At revision 11092.

#To update to a particular revision
svn update -r11090
At revision 11090.

#To update to a last committed version
svn up -r'COMMITTED'
At revision 11079.

#Change to a tagged version - to release 1.02
svn switch http://code.djangoproject.com/svn/django/tags/releases/1.0.2/

#Change to any branch
svn switch http://code.djangoproject.com/browser/django/branches/soc2009
</code></pre>

<p><code>svn switch</code> commands talk to the central servers and can be time consuming.</p>

<h3>Possible shortcomings of using source and symbollic links:</h3>

<p>Setuptools distribution adds to the python standard library <a href="http://docs.python.org/distutils/">Distutils</a> module, by adding a lot of functionality, among others that stores the package meta data like the version, location of download. If you perform</p>

<pre><code>easy_install django
</code></pre>

<p>after installing it by source as above, <code>easy_install</code> again downloads the latest released version of django 1.02, listed in the Python Package Index, as it hasn&#8217;t been informed of django installation.</p>

<p>If you are not going to use <code>easy_install</code> at all, this isn&#8217;t a problem; but it is good to also update setup tools that a version of this application exists, if you at all need. You can then use the <code>pkg_resources</code> module installed with setup tools distibution, to query to find all the installed applications, from python.</p>

<p>If the application contains a <code>setup.py</code> file, you could manually inform setup tools to update using the following command</p>

<pre><code>python setup.py develop
</code></pre>

<h3>The workflow</h3>

<p>To install packages, in a way with high control following needs to be done:</p>

<pre><code>* Checkout the repository
* Add a symbollic link to the repository
* Update setup tools of this installation.
</code></pre>

<h3>Enter PIP</h3>

<p>PIP is a package management tool that does the workflow we need, well. It automatically checks out from the repos and runs <code>python manage.py develop</code> and updates few other resources, so that python package management tools in the system are well aware of the installed packages.</p>

<p>If you are checking out the source and creating symbolic links, it is kind of awkward to have to create symbolic links all the time; Pip automates that. Pip also updates the setuptools with the metadata of the application, so that next time if you ask the same application to be installed, via <code>easy_install</code> or <code>pip</code>, it doesn&#8217;t download and install again.</p>

<p>So the following command:</p>

<pre><code>pip install -e hg+http://bitbucket.org/ubernostrum/django-registration/#egg=django_registration
</code></pre>

<ul>
<li>Clones the mercurial repository django-registration locally, into <code>Env/src/django_registration</code></li>
<li>Creates the required symbollic links in the python path, in this case in the <code>site-packages</code> folder</li>
<li>Updates the local package management tools by setup tools of the new package.</li>
</ul>

<p><code>-e</code> option tells pip to install the package as editable, that is to leave the repository undeleted. The <code>hg+</code> and <code>egg=django_registration</code> indicate the repository and the local folder to install to.</p>

<p>Pip works well with git, SVN, Hg an Bzr. Provided you inform the pip of the repository and the folder name, pip completes the work-flow.</p>

<p>Since the source is present in the <code>Env/src</code> folder,  along with the SVN, Git or Hg data, one can modify the versions using version control systems, as illustrated in some of the commands above</p>

<h3>Multiple environments</h3>

<p>Most often the requirement will be just to update the package into the latest version, for which simple revision control update commands seem good enough. Its good to also mess around with the code changing into different versions and trying different things.</p>

<p>But if you seem to be changing of the versions too often, for compatibility between different environments, you might want to using <a href="http://pypi.python.org/pypi/virtualenv">virtualenv</a>, that isolates a python working environment. <a href="http://pypi.python.org/pypi/virtualenvwrapper">virtualenvwrapper</a> adds a bash wrapper to use virtualenv conviniently.</p>

<hr />

<p>Do you also want your app development managed well? <a href="http://uswaretech.com/contact/">Look us up</a></p>


<p>Related posts:<ol><li><a href='http://uswaretech.com/blog/2009/12/python-metaclasses-and-how-django-uses-them/' rel='bookmark' title='Permanent Link: Python metaclasses and how Django uses them'>Python metaclasses and how Django uses them</a></li>
<li><a href='http://uswaretech.com/blog/2009/06/bing-python-api/' rel='bookmark' title='Permanent Link: Python Wrapper on Bing API'>Python Wrapper on Bing API</a></li>
<li><a href='http://uswaretech.com/blog/2009/09/python-tutorial-slides/' rel='bookmark' title='Permanent Link: Beginning python'>Beginning python</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://uswaretech.com/blog/2009/06/better-python-package-management-using-source-and-version-control-systems/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Understanding decorators</title>
		<link>http://uswaretech.com/blog/2009/06/understanding-decorators/</link>
		<comments>http://uswaretech.com/blog/2009/06/understanding-decorators/#comments</comments>
		<pubDate>Tue, 23 Jun 2009 14:04:57 +0000</pubDate>
		<dc:creator>shabda</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://uswaretech.com/blog/?p=556</guid>
		<description><![CDATA[If you used Django for any length of time, you would have come across the login_required decorator. You write @login_required before a view, and it magically becomes accessible only to authenticated users. Decorators were introduced in python 2.4. PEP 318 is the PEP describing it. At the simplest decorators are nothing but callables returning other [...]


Related posts:<ol><li><a href='http://uswaretech.com/blog/2009/02/understanding-datetime-tzinfo-timedelta-timezone-conversions-python/' rel='bookmark' title='Permanent Link: Understanding DateTime, tzinfo, timedelta &amp; TimeZone Conversions in python'>Understanding DateTime, tzinfo, timedelta &amp; TimeZone Conversions in python</a></li>
<li><a href='http://uswaretech.com/blog/2008/10/dynamic-forms-with-django/' rel='bookmark' title='Permanent Link: Dynamic forms with Django'>Dynamic forms with Django</a></li>
<li><a href='http://uswaretech.com/blog/2009/07/arent-django-signals-a-little-like-comefrom/' rel='bookmark' title='Permanent Link: Aren&#8217;t django signals a little like comefrom?'>Aren&#8217;t django signals a little like comefrom?</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p></p><p>If you used Django for any length of time, you would have come across the
<code>login_required</code> decorator. You write <code>@login_required</code> before a view, and it
magically becomes accessible only to authenticated users.</p>

<p>Decorators were introduced in python 2.4. <a href="http://www.python.org/dev/peps/pep-0318/">PEP 318</a>
is the <a href="http://www.python.org/dev/peps/">PEP</a> describing it. At
the simplest decorators are nothing but callables returning other callables, and
the decorator syntax <code>@decorator</code> is nothing but <code>foo = bar(foo)</code>, where both
<code>bar</code> and <code>foo</code> are callables.</p>

<p>Let us see some decorators in action.</p>

<pre><code>In [1]: def good_function():
   ...:     print 'I am a good function'
   ...:     
   ...:     

In [2]: def decorator(orig_func):
   ...:     def bad_func():
   ...:         print 'I am a bad function'
   ...:     return bad_func
   ...: 

In [3]: good_function = decorator(good_function)

In [4]: good_function()
I am a bad function

In [5]: @decorator
   ....: def good_function2():
   ....:     print 'I am a good function'
   ....:     
   ....:     

In [6]: good_function2()
I am a bad function
</code></pre>

<p>So you can see that the decorated function depended only on the value of the
function returned by the decorator.</p>

<p>Here we discarded the function we were passed. Any useful decorator, <em>decorates</em>
the original function, so it would use the original function. Let us see an
actual decorator which may be useful.</p>

<pre><code>def is_val_positive_deco(orig_func):
        def temp_func(val):
                if val &lt; 0:
                        return 0
                else:
                        return orig_func(val)
        return temp_func

@is_val_positive_deco
def sqrt(val):
        import math
        return math.pow(val, (1.0/2))

print sqrt(-1)
print sqrt(4)
</code></pre>

<p>Here we defined an decorator <code>is_val_positive_deco</code> which will make functions
return 0, if the argument passed is negative. We can use this decorator to guard
against MathErrors.</p>

<h2>Class based decorators</h2>

<p>Decorators are just callables, and hence can be a class which has <code>__call__</code>
method. Sometimes they are easier to understand and reason about(than decorators
written as functions).
Lets see one,</p>

<pre><code>class LogArgumentsDecorator(object):
        def __init__(self, orig_func):
                self.orig_func = orig_func
                print 'started logging: %s' % orig_func.__name__

        def __call__(self,  *args, **kwargs):
                print 'args: %s' % args
                print 'kwargs:%s'% kwargs
                return self.orig_func(*args, **kwargs)

@LogArgumentsDecorator      
def sum_of_squares(a, b):
        return a*a + b*b

print sum_of_squares(3, b=4)
</code></pre>

<p>This outputs,</p>

<pre><code>started logging: sum_of_squares
args: 3
kwargs:{'b': 4}
25
</code></pre>

<p>Lets see what happens when we do,</p>

<pre><code>@LogArgumentsDecorator      
def sum_of_squares(a, b):
</code></pre>

<p>This is equivalent to</p>

<pre><code>sum_of_squares = LogArgumentsDecorator(sum_of_squares)
</code></pre>

<p>At this point, we created a new LogArgumentsDecorator object, so
<code>LogArgumentsDecorator.__init__(self, sum_of_squares)</code> gets called. Hence
<code>print 'started logging: %s' % orig_func.__name__</code> line is executed.</p>

<p>When we do <code>sum_of_squares(...)</code></p>

<p><code>LogArgumentsDecorator.__call__</code> gets called with the passed values, where we
print the arguments and call the original function.</p>

<p>Here is one more example of a class based decorator. Here we rewrite(sort of,
anyway) Django&#8217;s login_required decorator as a class based decorator.</p>

<pre><code>class LoginRequiredDecorator(object):
def __init__(self, orig_func):
    self.orig_func = orig_func

def __call__(self, request, *args, **kwargs):
    if request.user.is_authenticated():
        self.orig_func(request, *args, **kwargs)
    else:
        return HttpResponseRedirect(reverse('...'))
</code></pre>

<p>Similar to above, it takes the view function, during <code>__init__</code>. When the request
comes, <code>__call__</code> makes sure that user is authenticated, and takes action
appropriately.</p>

<p>Resources
* <a href="http://wiki.python.org/moin/PythonDecoratorLibrary">Decorator Library</a>
* <a href="http://www.python.org/dev/peps/pep-0318/">Pep 318</a></p>

<hr />

<p>Subscribe to <a href="http://feeds.feedburner.com/UswareBlog">The Uswaretech Blog</a> where we will be writing the next part of this tutorial explaining more complex decorators, decorators which take arguments, decorator factories and more. Or follow us on <a href="http://twitter.com/uswaretech">twitter</a>.</p>


<p>Related posts:<ol><li><a href='http://uswaretech.com/blog/2009/02/understanding-datetime-tzinfo-timedelta-timezone-conversions-python/' rel='bookmark' title='Permanent Link: Understanding DateTime, tzinfo, timedelta &amp; TimeZone Conversions in python'>Understanding DateTime, tzinfo, timedelta &amp; TimeZone Conversions in python</a></li>
<li><a href='http://uswaretech.com/blog/2008/10/dynamic-forms-with-django/' rel='bookmark' title='Permanent Link: Dynamic forms with Django'>Dynamic forms with Django</a></li>
<li><a href='http://uswaretech.com/blog/2009/07/arent-django-signals-a-little-like-comefrom/' rel='bookmark' title='Permanent Link: Aren&#8217;t django signals a little like comefrom?'>Aren&#8217;t django signals a little like comefrom?</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://uswaretech.com/blog/2009/06/understanding-decorators/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>An Interview with Adrian Holovaty &#8211; Creator of Django</title>
		<link>http://uswaretech.com/blog/2008/06/an-interview-with-adrian-holovaty/</link>
		<comments>http://uswaretech.com/blog/2008/06/an-interview-with-adrian-holovaty/#comments</comments>
		<pubDate>Mon, 23 Jun 2008 22:06:06 +0000</pubDate>
		<dc:creator>shabda</dc:creator>
				<category><![CDATA[django]]></category>
		<category><![CDATA[interviews]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://42topics.com/blog/?p=69</guid>
		<description><![CDATA[Adrian Holovaty is the co-creator of Django, author of the Django book and is currently the BDFL of Django along with Jacob Kaplan-Moss. He studied journalism at University of Missouri–Columbia and has worked with many news sites including Lawrence Journal World and Washington Post. He currently works at EveryBlock, a startup he founded. Shabda: Would [...]


Related posts:<ol><li><a href='http://uswaretech.com/blog/2008/05/an-interview-with-jacob-kaplan-moss-creator-of-django/' rel='bookmark' title='Permanent Link: An Interview with Jacob Kaplan-Moss &#8211; Creator of Django'>An Interview with Jacob Kaplan-Moss &#8211; Creator of Django</a></li>
<li><a href='http://uswaretech.com/blog/2008/04/interview-with-james-bennett-django-release-manager/' rel='bookmark' title='Permanent Link: Interview with James Bennett &#8211; Django release manager'>Interview with James Bennett &#8211; Django release manager</a></li>
<li><a href='http://uswaretech.com/blog/2008/05/an-interview-with-russell-keith-magee/' rel='bookmark' title='Permanent Link: An interview with Russell Keith-Magee &#8211; Django core contributor'>An interview with Russell Keith-Magee &#8211; Django core contributor</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p></p><p><a href="http://www.holovaty.com/">Adrian Holovaty</a> is the co-creator of Django, author of the Django book and is currently the BDFL of Django along with Jacob Kaplan-Moss. He studied journalism at <a href="http://www.missouri.edu/about/mufacts.php">University of Missouri–Columbia</a> and has worked with many news sites including <a href="http://www2.ljworld.com/">Lawrence Journal World</a> and <a href="http://www.washingtonpost.com/">Washington Post</a>. He currently works at <a href="http://everyblock.com/">EveryBlock</a>, a startup he founded.</p>

<hr />

<p><strong>Shabda:</strong> Would you tell a little about yourself? You majored in Journalism, how did you move to Programming?</p>

<p><strong>Adrian:</strong> Sure! I have a dual background in journalism and computer science. I
intended to get a degree in journalism and a minor in computer
science, but things got a little off track. I heard from a
professional colleague that a certain Web site would probably hire me
if I graduated a semester early, so I hurriedly dropped my CS minor
and got special permission to graduate early &#8212; but once the time came
to ask for that job, the company was in the middle of a hiring freeze
and didn&#8217;t have a position for me. So, in hindsight, I should&#8217;ve stuck
with the minor, but things ended up working out OK.</p>

<p>Because journalism and computer science don&#8217;t normally go together,
I&#8217;ve had some success in this silly little niche of employing Web
development in news organizations &#8212; &#8220;journalism via computer
programming.&#8221; Professionally, I&#8217;ve always worked as a Web developer at
news organizations, up until my current gig, which is to run
<a href="http://everyblock.com">EveryBlock</a>. But in its own way, it&#8217;s a news
organization as well.</p>

<p>Aside from all of that, I&#8217;m quite into music, particularly gypsy jazz,
which is the music of Django Reinhardt (hence the name of the Web
framework). I just recently attended a <a href="http://djangoinjune.com">week-long gypsy jazz guitar
camp in Massachusetts</a> and had a tremendous time
staying up until early hours of the morning jamming with great
musicians from various parts of the world. If money were no object, I
would love to play music full time. In the meantime, I&#8217;ll settle for
posting <a href="http://youtube.com/adrianholovaty">YouTube videos of my guitar playing</a>, for an audience that seems to be
comprised mostly of 16-year-old boys who constantly pester me for
transcriptions of my arrangements.</p>

<p>I live with my wife in the beautiful city of Chicago.</p>

<p><strong>Shabda:</strong> What are your current roles and responsibilities at Django?</p>

<p><strong>Adrian:</strong> Well, I co-created Django back in 2003 with my friend <a href="http://simonwillison.net/">Simon Willison</a>
while we were working together. Now, along with <a href="http://www.jacobian.org/">Jacob Kaplan-Moss</a>, I&#8217;m
Benevolent Dictator For Life of the project &#8212; a title we shamelessly
ripped off from Guido/Python. This means that I have a hand in all
sorts of things, from high-level API design to checking in patches and
fixing bugs. I&#8217;ve touched probably every bit of the framework over the
years, including implementing the initial ORM (back when it was a code
generator!), pair-programming the original Django template system and
URLconf/view framework with Simon and building the original admin
application with design help from Wilson Miner.</p>

<p>One of the things I enjoy the most is writing documentation &#8212; both
because I like technical writing and because I cannot stand bad
open-source documentation.</p>

<p><strong>Shabda:</strong> Can you describe the philosophy behind Django. What are its overarching goals?</p>

<p><strong>Adrian:</strong> A couple of years ago, I wrote the &#8220;<a href="http://www.djangoproject.com/documentation/design_philosophies/">Design philosophies</a>&#8221; document,
which sums up the main points nicely.</p>

<p>Generally, the goal is to make Web development fast, fun and easy for
the developer, while keeping performance as fast as possible and code
as easy to understand as possible.</p>

<p><strong>Shabda:</strong> How did the move at WorldOnline from PHP to Python happen? Why did you start from scratch (which finally lead to creation of Django), instead of using something like Zope?</p>

<p><strong>Adrian:</strong> Simon and I had been big fans of <a href="http://diveintomark.org/">Mark Pilgrim</a> (and still are!), and
we&#8217;d read his online book &#8220;<a href="http://www.diveintopython.org/">Dive Into Python</a>.&#8221; This was around the same
time that the PHP &#8220;infrastructure&#8221; I&#8217;d developed had begun to feel
really, really crufty, so&#8230;one day we just decided to start using
Python! It&#8217;s quite nice working at a small organization with a very
loose management structure; our boss, Rob Curley, was cool enough to
let the developers themselves decide which technologies to use, as
long as the work got done. &#8220;I don&#8217;t care how the sausage is made,&#8221; he
always used to say.</p>

<p>We looked at the existing Python Web frameworks/libraries, but none of
them felt 100% right to us. Simon and I are both quite into best
practices, such as clean URLs, proper use of GET vs. POST, etc., so we
were very picky in our analysis of those existing tools.</p>

<p><strong>Shabda:</strong> Can you tell us about <a href="http://everyblock.com/">Everyblock</a>? Why did you choose to create your own mapping engine instead of using something like Google Maps? How hard has it been creating a new mapping engine?</p>

<p><strong>Adrian:</strong> EveryBlock is the project I lead for my day job. It&#8217;s funded by a
two-year grant from the <a href="http://www.knightfoundation.org/">Knight Foundation</a>, and the goal is to
experiment with block-specific news &#8212; that is, the site lets you
enter an address (currently only in Chicago, New York City and San
Francisco) and view recent news within a very tight radius of that
address. I&#8217;m pretty confident it&#8217;s the most granular attempt at local
news ever attempted on the Web. Nobody else is crazy enough to do it,
I guess!</p>

<p>We do a TON of work collecting local information, normalizing it and
pulling it together for people in one place. A large part of what we
publish is government data such as crime reports, restaurant
inspections, building permits, business licenses&#8230;and even local
movie filmings. Much of this stuff either is buried in &#8220;deep Web&#8221;
government databases or has never before been available online. A
second part of what we do is detecting addresses and locations in news
articles and blog entries. Plus, we pull in various other geographic
Web stuff like Flickr photos and Yelp reviews.</p>

<p>All in all, our goal is to show you recent, geographically relevant
stuff that you might not have heard about. Say the local newspaper
wrote something about your neighborhood on page B-23 &#8212; would you
really have noticed that article? Say there was an aggravated assault
on your block &#8212; would you really have remembered to check your police
department&#8217;s crime-reports Web site on a daily basis? That&#8217;s the basic
philosophy.</p>

<p>Regarding our custom mapping engine&#8230;Let&#8217;s face it: Google Maps is so
passe. As one of the original Google Maps mashup guys (I developed
<a href="http://chicagocrime.org">chicagocrime.org</a> by reverse-engineering Google&#8217;s JavaScript, <em>before</em>
the API was released), I have all the respect in the world for what
Google has done to invigorate the world of Web maps. But it&#8217;s time to
take the next step. The Google Maps API doesn&#8217;t give you any control
over the colors of the map tiles, or change the fonts in street
labels, or disable building footprints, or hide one-way street markers
or subway stations or bus stops or any of the other stuff that&#8217;s
essentially hard-coded in the map. So, at EveryBlock, we rolled our
own maps so we could have much, much more fine-grained control over
all of these things. Not to mention it&#8217;s a great way to differentiate
ourselves from the 2.5 million boring, same-old-yellow-blue-orange
Google Maps mashups out there.</p>

<p>Paul Smith from the EveryBlock team has written an article at <a href="http://www.alistapart.com/articles/takecontrolofyourmaps">A List
Apart with more of the technical specifics</a>.</p>

<p><strong>Shabda:</strong> As per the <a href="http://www.knightfoundation.org/grants/">Knight grant</a> rules, you would be releasing the code for Everyblock next year. Would you not be giving away your secret sauce? How do you plan to maintain competitive advantage once that code is freely
 avaliable under a permissive license?</p>

<p><strong>Adrian:</strong> Our competitive advantage is that we&#8217;re an incredible team, and I&#8217;m
sure we&#8217;ll come up with a way to feed our families.</p>

<p><strong>Shabda:</strong> What problems would you like Django to tackle after 1.0? What big features would you be most interested in having in Django, after it hits 1.0?</p>

<p><strong>Adrian:</strong> Generally I&#8217;d like to add higher and higher levels of abstraction to
the framework. The Django admin application is a good example of that
&#8211; it&#8217;s not just an abstraction of an HTTP request; it&#8217;s an
abstraction of an entire Web application! We should do more of those.</p>

<p><strong>Shabda:</strong> What is one thing about Django which you absolutely love, and one thing which you think Django should do differently?</p>

<p><strong>Adrian:</strong> I love the way URLconfs work &#8212; like a table of contents for your Web
app. I also love template inheritance. I don&#8217;t love the fact that
we&#8217;re generally slow in keeping up with tickets and feature requests.</p>

<p><strong>Shabda:</strong> A lot of people these days have to evaluate between Django and ROR. How can they make this decision? When should Adrian Holovaty use ROR? When should DHH use Django?</p>

<p><strong>Adrian:</strong> My answer is simple: Try out both frameworks and see which one you like better.</p>

<p><strong>Shabda:</strong> Does Django need to market itself differently? What can Django community do for this?</p>

<p><strong>Adrian:</strong> I&#8217;m comfortable with the amount of attention (or lack thereof,
depending on your perspective) that our project gets. I&#8217;m comfortable
with the size of the community. I&#8217;m comfortable with the fact that the
right people have found out about it through word of mouth, books,
blogs, <a href="http://code.google.com/appengine/">Google App Engine</a> or wherever else. If things continue at their
current rate, we&#8217;ll continue to do just fine, as a healthy open-source
project.</p>

<p>The one thing I&#8217;d ask the community to do is to continue staying
civil, polite and approachable.</p>

<p><strong>Shabda:</strong> What does the phrase &#8216;journalism via computer programming&#8217; mean? How can these two divergent fields be tied together?</p>

<p><strong>Adrian:</strong> &#8220;Journalism via computer programming,&#8221; in my opinion, is when a
journalist writes code to tell a story. Instead of talking on the
phone with sources to gather facts, this could involve screen-scraping
Web sites to gather raw data. Instead of writing a newspaper article,
this could involve building a database-driven Web site.</p>

<p>Journalism has several subdisciplines &#8212; photography, information
graphics, video. I advocate that computer programming should be
another one of those subdisciplines. Just as a newspaper employs
photographers and graphic artists, it should employ programmers who
help gather information and tell stories with it.</p>

<p><strong>Shabda:</strong> How can traditional journalists do more &#8216;journalism via computer programming&#8217;? How can programmers do more &#8216;journalism via computer
programming&#8217;? Is it easier for Programmers to move to this field, or for
Journalists?</p>

<p><strong>Adrian:</strong> I believe it&#8217;s easier for programmers to become journalists than it is
for journalists to become programmers, but both sides need to gain an
appreciation for the other in order for this sort of thing to happen
more often. Fortunately, some news organizations are starting to hire
developers with this in mind, and some geeks are realizing journalism
is a great, (mostly) pure field that lets you improve the world
through information.</p>

<p>One concrete thing programmers can do is to look for jobs at news
organizations, which desperately need technical talent. Developers,
you will be loved, you will be treated like geniuses, and your
non-techie coworkers will be very easily impressed!</p>

<p>Another route programmers can take is to get training in journalism &#8211;
in fact, Northwestern University&#8217;s journalism school is giving out
full-tuition scholarships for <a href="http://www.medill.northwestern.edu/admissions/programmers.html">programmers who want to learn
journalism</a>.</p>

<p><strong>Shabda:</strong> Thanks Adrian.</p>

<hr />

<p>This was Adrian&#8217;s interview, the last in django-interviews series. But we have a lot of interesting things coming up, so <a href="http://42topics.com/blog/feed/">stay tuned</a>.</p>


<p>Related posts:<ol><li><a href='http://uswaretech.com/blog/2008/05/an-interview-with-jacob-kaplan-moss-creator-of-django/' rel='bookmark' title='Permanent Link: An Interview with Jacob Kaplan-Moss &#8211; Creator of Django'>An Interview with Jacob Kaplan-Moss &#8211; Creator of Django</a></li>
<li><a href='http://uswaretech.com/blog/2008/04/interview-with-james-bennett-django-release-manager/' rel='bookmark' title='Permanent Link: Interview with James Bennett &#8211; Django release manager'>Interview with James Bennett &#8211; Django release manager</a></li>
<li><a href='http://uswaretech.com/blog/2008/05/an-interview-with-russell-keith-magee/' rel='bookmark' title='Permanent Link: An interview with Russell Keith-Magee &#8211; Django core contributor'>An interview with Russell Keith-Magee &#8211; Django core contributor</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://uswaretech.com/blog/2008/06/an-interview-with-adrian-holovaty/feed/</wfw:commentRss>
		<slash:comments>23</slash:comments>
		</item>
	</channel>
</rss>
