<?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; tips</title>
	<atom:link href="http://uswaretech.com/blog/category/tips/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>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>Using bpython shell with django (and some Ipython features you should know)</title>
		<link>http://uswaretech.com/blog/2009/12/using-bpython-shell-with-django-and-some-ipython-features-you-should-know/</link>
		<comments>http://uswaretech.com/blog/2009/12/using-bpython-shell-with-django-and-some-ipython-features-you-should-know/#comments</comments>
		<pubDate>Sat, 12 Dec 2009 16:17:37 +0000</pubDate>
		<dc:creator>lakshman</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[utilities]]></category>
		<category><![CDATA[bpython]]></category>
		<category><![CDATA[ipython]]></category>

		<guid isPermaLink="false">http://uswaretech.com/blog/?p=825</guid>
		<description><![CDATA[What is bpython? bpython is a fancy interface to the Python interpreter for Unix-like operating system. says the bpython home page. It provides syntax highlighting, auto completion, auto-indentation and such stuff. Unlike iPython, which implements then entire shell functions and emulates the standard python shell, and adds enhancements, bpython just adds features on top of [...]


Related posts:<ol><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>
<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><h3>What is bpython?</h3>

<blockquote>
  <p>bpython is a fancy interface to the Python interpreter for Unix-like operating system.</p>
</blockquote>

<p>says the <a href="http://bpython-interpreter.org/">bpython</a> home page. It provides syntax highlighting, auto completion, auto-indentation and such stuff.</p>

<p>Unlike <a href="http://ipython.scipy.org/moin/">iPython</a>, which implements then entire shell functions and emulates the standard python shell, and adds enhancements, bpython just adds features on top of the existing python shell functionality, using the curses module.</p>

<p><img src="http://i.imgur.com/cqky1.png" alt="bpython" /></p>

<p>The &#8220;killer feature&#8221; of bpython is, as you can see from the image above, the IDE like prompting of the function parameters and the doc string of the function dynamically. I have always thought, what <a href="http://www.jetbrains.com/idea/">IntellijIDEA</a> is to Java, IPython is to Python*. But bpython makes it more so, in terms of the code completion, which adds a lot of value to a <em>ramping up developer</em>.</p>

<p>The only Python IDE that provides Source Assistant and Go-To-Source functionality conveniently, is the commercial one, <a href="http://www.wingide.com/wingide">Wing IDE Professional</a>. Even with that, since all the defined models are replaced (by using meta-classes) in the runtime, that source assistant is not perfect. Newer versions of Wing seems to claim to obtain data dynamically at the runtime, but its not always comfortable to write code, keeping the IDE in a breakpoint. But hey, bpython provides all these for free!</p>

<h3>But I already use Ipython</h3>

<p>You do? So do I. In fact, I am a Power Ipython user, I use all kinds of <a href="http://ipython.scipy.org/doc/stable/html/interactive/reference.html#magic-command-system">%magic</a> functions: %whos, <a href="http://ipython.scipy.org/doc/stable/html/interactive/reference.html#session-logging-and-restoring">%logstart</a>, %bookmark, %ed  and sometimes use Ipython as an alternative even to bash: %cd, %ls, %ll. And even for doc testing: <a href="http://ipython.scipy.org/doc/stable/html/interactive/reference.html#pasting-of-code-starting-with-or">%doctest_mode</a>, copy-pasting %hist -n or running some code module in the interpreter namespace: %run -i and searching code %psearch. You can also give any arbitrary bash(or your default shell) command by escaping it with !. Oh, ?, ?? and / are of course the starters.</p>

<p>In fact did you know, you could get to ipython shell within any arbitrary place within your django code? Just use the following:</p>

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

<p>and then call ipython() anywhere within your view, model, forms and you will be dropped to the shell. Its <a href="http://aymanh.com/python-debugging-techniques">like ipdb.set_trace()</a> only better (unless you want to step through, that is).</p>

<h3>The Python readline bug</h3>

<p>The Python version 2.6.4 (the version that is shipped with Ubuntu 9.10), introduced a <a href="http://bugs.python.org/issue5833">readline bug</a> that adds spaces after tab completion. This bug also affects the Ipython, as it uses the same readline module. If you spend a lot of time on the shell (if you use python, you must, right?), it is very annoying to backspace after each tab, all the time.</p>

<p>Although the bug got fixed pretty soon, it hasn&#8217;t yet made it to any release that ubuntu updates to. There are ways to workaround this problem, by fixing it at the python level and at the Ipython level, many of them are discussed on the corresponding <a href="https://bugs.launchpad.net/ipython/+bug/470824">Ipython bug</a></p>

<h3>Using bpython with django</h3>

<p>Now that you want to use bpython with django, either because you like the auto completion, or because you find the read line bug annoying (and don&#8217;t want/care-enough to patch your python locally), or you just want to try it, how to do it?</p>

<p><code>django manage.py shell</code> unfortunately, drops only into the ipython shell (if you have ipython installed), and there is no straight forward way to get it to drop to bpython.</p>

<p>But there is still a way to use bpython with django. Just modify your ~/.bashrc to define a python startup environment variable</p>

<pre><code>export PYTHONSTARTUP=~/.pythonrc
</code></pre>

<p>And within it, setup the django environment, that is, do it here manually the thing that <code>python manage.py shell</code> would do for you:</p>

<pre><code>#.pythonrc
try:
    from django.core.management import setup_environ
    import settings
    setup_environ(settings)
    print 'imported django settings'
except:
    pass
</code></pre>

<p>This way, <code>bpython</code> or even just <code>python</code> on the command line, should import the django environment for you.</p>

<h3>Importing all models automatically into the shell</h3>

<p>But then, if you are possibly already used to <code>python manage.py shell_plus</code> (If you are not, you should be.) that is defined by <a href="http://wiki.github.com/django-extensions/django-extensions/current-command-extensions">django_command_extensions</a>.</p>

<p>So while we are at setting up the django environment, lets just also import all the models into the shell namespace, so that it is convenient to work. Following is some ugly quick hack to get it done.</p>

<script src="http://gist.github.com/231878.js?file=.pythonrc.py"></script>

<p>This can of course be improved upon. If you do it, just leave it in the comments! In fact it would be good if it also includes <code>from startup.py import *</code> in a try catch, so that, you can put some extra code into startup.py. Saving into startup.py from within a bpython shell is just a <code>Ctrl+s</code> anyway. That way each time you get to the shell, you can have the same expected environment; and it is quite easy to change that file.</p>

<p>*I know, I know, IPython doesn&#8217;t refactor code, nor build, nor does a million things that Intellij does, but <a href="http://dirtsimple.org/2004/12/python-is-not-java.html">Python is not Java</a> and basically both intend to enhance developer productivity. And I spend a lot of time on the IPython shell and find it to be a tool just like Intellij is a tool, for Java.</p>


<p>Related posts:<ol><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>
<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/12/using-bpython-shell-with-django-and-some-ipython-features-you-should-know/feed/</wfw:commentRss>
		<slash:comments>61</slash:comments>
		</item>
		<item>
		<title>Django quiz</title>
		<link>http://uswaretech.com/blog/2009/12/django-quiz/</link>
		<comments>http://uswaretech.com/blog/2009/12/django-quiz/#comments</comments>
		<pubDate>Thu, 03 Dec 2009 15:26:31 +0000</pubDate>
		<dc:creator>shabda</dc:creator>
				<category><![CDATA[django]]></category>
		<category><![CDATA[meta]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[quiz]]></category>

		<guid isPermaLink="false">http://uswaretech.com/blog/?p=786</guid>
		<description><![CDATA[A quick django quiz. Answers available tomorrow. Get it as a text file (django-quiz) or on google docs or read below. ### Easy 1. You have a class defined as class Post(models.Model): name = models.CharField(max_length=100) is_active = models.BooleanField(default=False) You create multiple objects of this type. If you do Post.objects.get(is_active=False), what exceptions is raised? a. MultipleObjectsReturned [...]


Related posts:<ol><li><a href='http://uswaretech.com/blog/2010/01/doing-things-with-django-forms/' rel='bookmark' title='Permanent Link: Doing things with Django forms'>Doing things with Django forms</a></li>
<li><a href='http://uswaretech.com/blog/2009/06/understanding-decorators/' rel='bookmark' title='Permanent Link: Understanding decorators'>Understanding decorators</a></li>
<li><a href='http://uswaretech.com/blog/2008/10/using-subdomains-with-django/' rel='bookmark' title='Permanent Link: Using subdomains with Django'>Using subdomains with Django</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p></p><p>A quick django quiz. Answers available tomorrow. Get it as a text file <a href='http://dl.dropbox.com/u/271935/django-quiz.txt'>(django-quiz)</a> or on <a href="http://docs.google.com/Doc?docid=0AYLjHVQq0A8aZGZ0NTRxOXBfMGhxY2g2ZDhk&amp;hl=en">google docs</a> or read below.</p>

<pre><code>### Easy

1. You have a class defined as

    class Post(models.Model):
        name = models.CharField(max_length=100)
        is_active = models.BooleanField(default=False)

You create multiple objects of this type. If you do
Post.objects.get(is_active=False),

what exceptions is raised?

a. MultipleObjectsReturned
b. ManyObjectsReturned
c. SyntaxError
d. MultipleModelReturned
e. ManyModelReturned

2. Where is the function render_to_response defined?

a. django.views
b. django.shortcuts
c. django.templates
d. django.contrib.templates
e. django.contrib.shortcuts

3. What is the default name for the table created for model named Post
in application blog

a. post_blog
b. blog_post
c. postblog
d. blogpost
e. Postblog

4. How do you send a 302 redirect using django?

a. return HttpRedirectResponse()
b. return HttpResponseRedirect()
c. return HttpRedirectResponse(permanent=True)
d. return HttpResponseRedirect(permanent=True)
e. return HttpRedirectResponse

5. In django.contrib.auth, Users passwords are kept in what form?
a. Plain text
b. Hashed
c. Encrypted
d. Hashed then encrypted
3. Encrypted then hashed

6. Which of the following is correct way to find out if a request uses
HTTP POST method?

a. request.is_post() == True
b. request.METHOD == 'post'
c. request.METHOD == 'POST'
d. request.method == 'post'
e. request.method == 'POST'

7. Generic views have access to request context.

a. True
b. False
c. Default is True but can be set to False by GENERIC_REQUEST_CONTEXT in settings.
d. Default is False but can be set to True by GENERIC_REQUEST_CONTEXT in settings.
e. Can not be determined without extra information.

8. The current released version of Django is

a. 0.96
b. 1.0
c. 1.1
d. 1.2
e. Vyper logix 2.0

9. Which of these is a correct context_processor?

a.

def featured_posts(request):
    return Post.objects.filter(is_featured=True)

b.

def featured_posts(request):
    return {'featured_posts': Post.objects.filter(is_featured=True)}

c.

def featured_posts(request, response):
    return Post.objects.filter(is_featured=True)

d.

def featured_posts(request, response):
    return {'featured_posts': Post.objects.filter(is_featured=True)}

e.     
def featured_posts(request, response):
    response.write('featured_posts'= Post.objects.filter(is_featured=True))

10. Which of the following is a valid Middleware?

a.

class LatestPostMiddleware:
    def process_request(request):
        request.latest_post = Post.objects.latest()

b.

class LatestPostMiddleware(django.middlewares.BaseMiddleWare):
    def process_request(request):
        request.latest_post = Post.objects.latest()

c.

class LatestPostMiddleware(django.middlewares.BaseMiddleWare):
    def process_request(request):
        return {'latest_post': Post.objects.latest()}

d.

class LatestPostMiddleware():
    def process_request(request):
        return {'latest_post': Post.objects.latest()}

e.

class LatestPostMiddleware():
    def process_request(request):
        request.write('latest_post'= Post.objects.latest())


#Moderate

11. In the model below which line can be removed for the class to work

class Post(models.Model):
    name = models.CharField(max_length = 100)#Line 1
    desc = models.TextField()#Line 2
    post = models.ForeignKey(Blog)#Line 3
    blog = models.ForeignKey(Blog)#Line 4

a. Line 1
b. Line 2
c. Line 3
d. Line 4
e. Either of line 3 or 4

12. Who can access the admin site in Django?

a. user with is_super_user True
b. user with is_staff True
c. user with is_admin True
d. Either of a or b
e. Either of a, b, c

13. Which of the following code is closest to login_required decorator in Django?

a.

def login_required2(request):
    if request.user.is_authenticated():
        return True
    else:
        return False

b.

def login_required2(request, view_func):
    def check_login(request):
        if request.is_authenticated() and request.has_permissions(request.REQUIRED_PERMISSIONS):
            return view_function(request)
        else:
            return HttpResponseRedirect('/login/')
    return check_login(view_func)

c.

def login_required2(request, view_func):
    def check_login(request):
        if request.is_authenticated():
            return view_function(request)
        else:
            return HttpResponseRedirect('/login/')
    return check_login(view_func)

d.

def login_required2(view_func):
    def new_func(request):
        if request.user.is_authenticated():
            return view_func(request)
        else:
            return HttpResponseRedirect('/login/')
    return new_func


e.

def login_required2(view_func):
    def new_func(request):
        if request.user.is_authenticated() and request.has_permissions(request.REQUIRED_PERMISSIONS):
            return view_func(request)
        else:
            return HttpResponseRedirect('/login/')
    return new_func


14. Which of the following is a valid method to model Many to many relation ship in Django?

a.

class Foo(models.Model):
    bar = models.ManyToManyField(Bar)

class Bar(models.Model):
    foo = models.ManyToManyField(Foo)

b.

class Foo(models.Model):
    bar = models.ForeignKey(Bar)

class Bar(models.Model):
    foo = models.ForeignKey(Foo)

c.

class Foo(models.Model):
    bar = models.ManyToManyField(Bar)

class Bar(models.Model):
    pass

d. both B and C

e. All a, b, c

15. Which of the following is not included by default in TEMPLATE_CONTEXT_PROCESSORS

a. django.core.context_processors.auth
b. django.core.context_processors.debug
c. django.core.context_processors.i18n
d. django.core.context_processors.media
e. django.core.context_processors.request

16. Which of these is the currect way to validate uniqueness of a field named "slug" in a form
subclassing django.form.Forms.

a.

def clean(self):
    try:
        Post.objects.get(slug = self.cleaned_data['slug'])
        raise forms.Error(ValidationError, 'This slug already exists')
    except Post.DoesNotExist:
        return self.cleaned_data


b.

def clean(self):
    try:
        Post.objects.get(slug = self.cleaned_data['slug'])
        raise ValidationError('This slug already exists')
    except Post.DoesNotExist:
        return self.cleaned_data

c.

def clean_slug(self):
    try:
        Post.objects.get(slug = self.cleaned_data['slug'])
        raise forms.Error(ValidationError, 'This slug already exists')
    except Post.DoesNotExist:
        return self.cleaned_data


d.

def clean_slug(self):
    try:
        Post.objects.get(slug = self.cleaned_data['slug'])
        raise ValidationError('This slug already exists')
    except Post.DoesNotExist:
        return self.cleaned_data

e.

17. To add custom commands to your project setup, you need to,

1. Add management/command/commandname.py to your django app.
2. Add management/command/commandname.py to your django project.
3. Add command/commandname.py to your django app.
4. Add command/commandname.py to your django project.
5. Add management/command/manage.py to yout django project.

18. You want to enable caching for Django pages for AnonymousUser, which of these
is a valid way to do this.

a.


MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.middleware.cache.CacheMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
)

b.

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.cache.CacheMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
)

c.

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.middleware.cache.CacheMiddleware',
)

d.

MIDDLEWARE_CLASSES = (
    'django.middleware.cache.CacheMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
)

e.

MIDDLEWARE_CLASSES = (
    'django.middleware.cache.CacheMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
)

19.

Consider the urlconf given below

    from django.conf.urls.defaults import *

    urlpatterns = patterns('news.views',
        (r'^articles/2003/$', 'year_archive_2003'),
        (r'^articles/(\d{4})/', 'year_archive'),
        (r'^articles/2003/(\d{2})/$', 'month_archive_2003'),
        (r'^articles/(\d{4})/(\d{2})/', 'month_archive'),
        (r'^articles/(\d{4})/10/', 'month_archive_october'),
    )
What view is called when accessing /articles/2003/10/

a. year_archive_2003
b. year_archive
c. month_archive_2003
d. month_archive
e. month_archive_october

20.

Consider the urlpatterns.

    urlpatterns = patterns('blogapp.views',
        (r'^list/(?P&lt;year&gt;\d{4})/(?P&lt;month&gt;[a-z]{3})/$','archive_month'),
    )

Which if the following is a valid view function which will be called on accesing
/list/2009/jun/

a. def archive_month(request):
        ...

b. def archive_month(request, *args):

c. def archive_month(request, **kwargs):

d. def  archive_month(request, year, month,):

e. Both c and d


# Hard

None yet
</code></pre>

<hr />

<p><a href="http://twitter.com/uswaretech">Follow us on twitter</a> or <a href="http://feeds.feedburner.com/uswarearticles">subscribe to our blog</a></p>


<p>Related posts:<ol><li><a href='http://uswaretech.com/blog/2010/01/doing-things-with-django-forms/' rel='bookmark' title='Permanent Link: Doing things with Django forms'>Doing things with Django forms</a></li>
<li><a href='http://uswaretech.com/blog/2009/06/understanding-decorators/' rel='bookmark' title='Permanent Link: Understanding decorators'>Understanding decorators</a></li>
<li><a href='http://uswaretech.com/blog/2008/10/using-subdomains-with-django/' rel='bookmark' title='Permanent Link: Using subdomains with Django'>Using subdomains with Django</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://uswaretech.com/blog/2009/12/django-quiz/feed/</wfw:commentRss>
		<slash:comments>14</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>A response to Dropping Django</title>
		<link>http://uswaretech.com/blog/2009/08/a-response-to-dropping-django/</link>
		<comments>http://uswaretech.com/blog/2009/08/a-response-to-dropping-django/#comments</comments>
		<pubDate>Thu, 20 Aug 2009 11:58:37 +0000</pubDate>
		<dc:creator>shabda</dc:creator>
				<category><![CDATA[django]]></category>
		<category><![CDATA[rambling]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://uswaretech.com/blog/?p=662</guid>
		<description><![CDATA[Brandon Bloom yesterday wrote an interesting post titled dropping Django. Despite a lot of hand waving(We needed a pragmatic template language to replace Django&#8217;s idealistic one.), it raises some valid questions, so here is a solution to some of them. No support for hierarchical url creation. The simplest representation of nested urls I can think [...]


Related posts:<ol><li><a href='http://uswaretech.com/blog/2009/06/django-request-response-processing/' rel='bookmark' title='Permanent Link: Django Request Response processing'>Django Request Response processing</a></li>
<li><a href='http://uswaretech.com/blog/2008/10/generating-pdfs-with-django/' rel='bookmark' title='Permanent Link: Generating PDFs with Django'>Generating PDFs with Django</a></li>
<li><a href='http://uswaretech.com/blog/2009/12/django-quiz/' rel='bookmark' title='Permanent Link: Django quiz'>Django quiz</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p></p><p><a href="http://blog.brandonbloom.name/2009/08/dropping-django.html">Brandon Bloom</a> yesterday wrote an interesting post titled
dropping Django. Despite a lot of hand waving(We needed a pragmatic template language to replace Django&#8217;s idealistic one.),
it raises some valid questions, so here is a solution to some of them.</p>

<h4>No support for hierarchical url creation.</h4>

<p>The simplest representation of nested urls I can think of is a nested tuple. Lets represent,
the urls for a simple app by,</p>

<pre><code>&gt;&gt;&gt; tree_urls = ('', 'list',
...     ('edit/', 'edit', ('auto/', 'edit_auto')),
...     ('^add/', 'add'),
...     ('delete/', 'delete', ('hard/', 'delete_hard'))
...     )
</code></pre>

<p>Guess what, urls.py is <em>just a python module which excepts a variable names urlpatterns</em>.</p>

<p>Which means it is very easy to write a function which converts this nested structure to flat, structure.
Here is a quick attempt at that,</p>

<pre><code>def merge(url):
    full_url=[]
    for i, el in enumerate(url):
        if i%2==0:    
            full_url.append(el)
    full_url = ''.join(full_url)
    return full_url

def combineflatten(seq):
    items= tuple(item for item in seq if not isinstance(item, tuple))
    yield items
    for item in seq:
            if isinstance(item, tuple):
                for yielded in combineflatten(item):
                    yield items+yielded

def generate_flat_urls(tree_urls):
    """
    &gt;&gt;&gt; tree_urls = ('', 'list',
    ...     ('edit/', 'edit', ('auto/', 'edit_auto')),
    ...     ('^add/', 'add'),
    ...     ('delete/', 'delete', ('delete/', 'delete_hard'))
    ...     )

    &gt;&gt;&gt; generate_flat_urls(tree_urls)
    [('^$', 'list'), ('^edit/$', 'edit'), ('^edit/auto/$', 'edit_auto'), ('^^add/$', 'add'), ('^delete/$', 'delete'), ('^delete/delete/$', 'delete_hard')]
    """
    return [('^%s$'%merge(el), el[-1]) for el in tuple(combineflatten(tree_urls))]
</code></pre>

<p>With this you can use hierarchical urls in urls.py as,</p>

<pre><code>#All of urls.py
tree_urls = ('', 'list',
    ('edit/', 'edit', ('auto/', 'edit_auto')),
    ('^add/', 'add'),
    ('delete/', 'delete', ('delete/', 'delete_hard'))
    )

flat_urls = generate_flat_urls(tree_urls)

urlpatterns = patterns('app.views',
**flat_urls
)
</code></pre>

<h4>No support for per user, per resource authorisation.</h4>

<p>If you want to do this in a almost no-touching-the-existing-code way, replace all your <code>render_to_response</code> with,</p>

<pre><code>def render_with_auth_check(request, payload, request_context, *args, **kwrags):
    for el in payload.itervalues():
        try:
            has_auth = el.check_auth(request.user)
            if not has_auth:
                raise AuthFailException
        except ValueError:
            pass #Not all objects have check_auth
    return render_to_response(request, payload, request_context, *args, **kwrags)
</code></pre>

<p>And enable this middleware,</p>

<pre><code>class AuthFailHandlerMiddleware:
    def process_exception(self, request, exception):
        if type(exception) == AuthFailException:
            return render_to_response('accounts/login/', {}, RequestContext(request))
</code></pre>

<p>This assumes that all resources which are authorisation protected have a <code>.check_auth</code>,
but I cant see any way round that in any other way as well.</p>

<p>A different, and more robust way would be to write custom managers for all resources, which need authorization.</p>

<pre><code>class ResourceAuthManager(models.Manager):
    def get(self, user, *args, **kwargs):
        res = super(ResourceAuthManager, self).get(*args, **kwargs)
        try:
            has_auth = res.check_auth(request.user)
            if not has_auth:
                raise AuthFailException
        except ValueError:
            pass #Not all objects have check_auth

    ...
</code></pre>

<h4>The Django templating language is too constrained.</h4>

<p>Despite believing that Django templating language hits the sweet spot between, power
and convenience to <em>people who would be using it</em>, I never understood this argument,</p>

<p>If you are using sqlalchemy with Django you lose the admin, what do you lose if you use Jinja?</p>

<p>In particular what do you lose by replacing <code>render_to_response</code> with this,</p>

<pre><code>def render_jinja_to_response(template_name, payload):
    #This should probably go in settings.py
    from jinja2 import Environment
    env = Environment(loader=PackageLoader('app', 'templates'))

    template = env.get_template(template_name)
    response = template.render(**payload)
    return HttpResponse(response)
</code></pre>

<h4>Extending authentication &#8211; In particular enable loggin in with email</h4>

<p>Django authenticates against a <a href="http://www.google.co.in/search?hl=en&amp;client=firefox-a&amp;rls=org.mozilla%3Aen-US%3Aofficial&amp;hs=GGQ&amp;q=authentication+backends+site%3Adjangosnippets.org&amp;btnG=Search&amp;meta=&amp;aq=f&amp;oq=">wide range of backends</a>,
including Email, LDAP, Twitter and Facebook. While it is true that email backend doesn&#8217;t work
with Admin login, Admin is meant for use by staff and superusers, so why cant we provide
them usernames?</p>

<p>There are a few other questions raised, some of which I agree with(&#8220;Sadly, it[the admin app]
struggles a little bit with nullable fields and is tricky to customize.&#8221;), and some which I dont,
(&#8220;I will never write CSS by hand again.&#8221; &#8211; You shouldn&#8217;t be, someone else on your team should be doing that. )
But this line is interesting <code>Personally, I've developed a moderate fear of the word "framework"</code>.</p>

<p>This is arguable, but the way all frameworks essentially help you is by providing
Dependency Injection, (the Hollywood principle &#8211; Dont call me, I will call you).
Django provides that in a lot of ways. (You write a middleware, and django calls
it at appropriate places &#8211; Dont call me, I will call you), but still leaves something to be desired.
My ideal framework would be one where models are POPO and views are functions which return strings
. (Plain old python objects -like POJO). <a href="http://java.sun.com/developer/technicalArticles/J2EE/jpa/figure6.html">JPA</a> does this correctly,
but then JPA has the typing information, so maybe in python the only way to provide the required typing
information is <code>name=models.CharField(...)</code>. But the point being, we need better Dependency Inversion,
not less of it. We have been dow that path earlier, and it is a much harder way to build complex systems.</p>

<hr />

<p>Resources</p>

<ol>
<li><a href="http://gist.github.com/171016">This code on github</a></li>
<li><a href="http://stackoverflow.com/questions/1302653/convert-a-nested-dataset-to-a-flat-dataset-while-retaining-enough-data-to-conver">Discussion about converting the nested tuple to a flat one</a></li>
</ol>

<hr />

<p>My apologies if this post was aggressive, argumentative or disrespectful to the
original author. We generally try to stay away from controversial posts on this blog. But
I believe that this post raised some valid technical questions, and the intent of this
post was to answer them. For Django to develop the best way, we need more of these kind
of &#8220;What is wrong with Django&#8221; posts, not less, so my thanks to the original author. <img src='http://uswaretech.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>

<hr />

<p>Do you want to build <strong>Amazing Web Apps</strong>? <a href="http://uswaretech.com/contact/">We can help</a>.</p>


<p>Related posts:<ol><li><a href='http://uswaretech.com/blog/2009/06/django-request-response-processing/' rel='bookmark' title='Permanent Link: Django Request Response processing'>Django Request Response processing</a></li>
<li><a href='http://uswaretech.com/blog/2008/10/generating-pdfs-with-django/' rel='bookmark' title='Permanent Link: Generating PDFs with Django'>Generating PDFs with Django</a></li>
<li><a href='http://uswaretech.com/blog/2009/12/django-quiz/' rel='bookmark' title='Permanent Link: Django quiz'>Django quiz</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://uswaretech.com/blog/2009/08/a-response-to-dropping-django/feed/</wfw:commentRss>
		<slash:comments>54</slash:comments>
		</item>
		<item>
		<title>Django aggregation tutorial</title>
		<link>http://uswaretech.com/blog/2009/08/django-aggregation-tutorial/</link>
		<comments>http://uswaretech.com/blog/2009/08/django-aggregation-tutorial/#comments</comments>
		<pubDate>Tue, 18 Aug 2009 12:38:29 +0000</pubDate>
		<dc:creator>shabda</dc:creator>
				<category><![CDATA[aggreagtion]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[models]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://uswaretech.com/blog/?p=654</guid>
		<description><![CDATA[One of the new and most awaited features with Django 1.1 was aggregation. As usual, Django comes with a very comprehensive documentation for this. Here, I have tried to put this in how-to form. Jump to howtos or Get source on Github. Essentially, aggregations are nothing but a way to perform an operation on group [...]


Related posts:<ol><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/2008/04/new-tutorial-building-a-search-engine-with-appengine-and-yahoo/' rel='bookmark' title='Permanent Link: New tutorial &#8211; Building a search engine with Appengine and Yahoo'>New tutorial &#8211; Building a search engine with Appengine and Yahoo</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>One of the new and most awaited features with Django 1.1 was aggregation. As usual,
Django comes with a very <a href="http://docs.djangoproject.com/en/dev/topics/db/aggregation/">comprehensive documentation</a> for this. Here, I have tried to
put this in how-to form.</p>

<p><a href="#howtos">Jump to howtos</a> or <a href="http://github.com/uswaretech/Shiny-New-Django-1.1/tree/master">Get source on Github</a>.</p>

<p>Essentially, aggregations are nothing but a way to perform an operation on group of rows. In databases,
they are represented by operators as <code>sum</code>, <code>avg</code> etc.</p>

<p>To do these operations Django added two new methods to querysets.</p>

<ol>
<li><code>aggregate</code></li>
<li><code>annotate</code></li>
</ol>

<p>When you are have a queryset you can do two operations on it,</p>

<ol>
<li>Operate over the rowset to get a single value from it. (Such as sum of all salaries in the rowset)</li>
<li>Operate over the rowset to get a value for <em>each row in the rowset</em> via some related table.</li>
</ol>

<p>The thing to notice is that option 1, will create one row from rowset, while option 2 will
not change the number of rows in the rowset. If you are into analogies, you can think that
option 1 is like a <a href="http://docs.python.org/library/functions.html#reduce">reduce</a> and option 2 is like a <a href="http://docs.python.org/library/functions.html#map">map</a>.</p>

<p>In sql terms, aggregate is a operation(SUM, AVG, MIN, MAX), without a group by,
while annotate is a operation with a group by on rowset_table.id. (Unless explicitly overriden).</p>

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

<p>Ok enough talk, on to some actual work. Here is a fictional models.py representing
a HRMS application. We will use this to see how to use aggreagtion to solve
some common problems.</p>

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

class Department(models.Model):
    dept_name = models.CharField(max_length = 100)
    established_on = models.DateField()

    def __unicode__(self):
        return self.dept_name

class Level(models.Model):
    level_name = models.CharField(max_length = 100)
    pay_min = models.PositiveIntegerField()
    pay_max = models.PositiveIntegerField()

    def __unicode__(self):
        return self.level_name

class Employee(models.Model):
    emp_name = models.CharField(max_length = 100)
    department = models.ForeignKey(Department)
    level = models.ForeignKey(Level)
    reports_to = models.ForeignKey('self', null=True, blank=True)

    pay = models.PositiveIntegerField()
    joined_on = models.DateField()

class Leave(models.Model):
    employee = models.ForeignKey(Employee)
    leave_day = models.DateField()


"""
#Populate DB, so we can do some meaningful queries.
#Create Dept, Levels manually.
#Get the names file from http://dl.getdropbox.com/u/271935/djaggregations/names.pickle
#Or the whole sqlite database from http://dl.getdropbox.com/u/271935/djaggregations/bata.db
import random
from datetime import timedelta, date
import pickle
names = pickle.load(file('/home/shabda/names.pickle'))
for i in range(1000):
    emp = Employee()
    emp.name = random.choice(names)
    emp.department = random.choice(list(Department.objects.all()))
    emp.level = random.choice(Level.objects.all())
    try: emp.reports_to = random.choice(list(Employee.objects.filter(department=emp.department)))
    except:pass
    emp.pay = random.randint(emp.level.pay_min, emp.level.pay_max)
    emp.joined_on = emp.department.established_on + timedelta(days = random.randint(0, 200))
    emp.save()
"""

"""
employees = list(Employees.objects.all())
for i in range(100):
    employee = random.choice(employees)
    leave = Leave(employee = employee)
    leave.leave_day = date.today() - timedelta(days = random.randint(0, 365))
    leave.save()

"""
</code></pre>

<h4>Find the total number of employees.</h4>

<p>In sql you might want to do something like,</p>

<p><code>select count(id) from hrms_employee</code></p>

<p>Which becomes,</p>

<p><code>Employee.objects.all().aggregate(total=Count('id'))</code></p>

<p>If fact doing a <code>connection.queries.pop()</code> shows the exact query.</p>

<p><code>SELECT COUNT("hrms_employee"."id") AS "total" FROM "hrms_employee"</code></p>

<p>But wait, we have a builtin method already for that, <code>Employee.objects.all().count()</code>, so lets try something else.</p>

<h4>Find the total pay of employees.</h4>

<p>The CEO wants to find out what is the total salary expediture, this also converts
the queryset to a single value, so we want to <code>.aggregate</code> here.</p>

<p><code>Employee.objects.all().aggregate(total_payment=Sum('pay'))</code></p>

<p>Gives you the total amount you are paying to your employees.</p>

<h4>Find the total number of employees, per department.</h4>

<p>Here we want a value per row in queryset, so we need to use aggregate here. Also,
there would be one aggregated value per dpeartment, so we need to annotate Department
queryset.</p>

<p><code>Department.objects.all().annotate(Count('employee'))</code></p>

<p>If you are only interested in name of department and employee count for it, you can do,
<code>Department.objects.values('dept_name').annotate(Count('employee'))</code></p>

<p>The sql is</p>

<pre><code>SELECT "hrms_department"."dept_name", COUNT("hrms_employee"."id") AS "employee__count" FROM "hrms_department" LEFT OUTER JOIN "hrms_employee" ON ("hrms_department"."id" = "hrms_employee"."department_id") GROUP BY "hrms_department"."dept_name"
</code></pre>

<h4>Find the total number of employees, for a specific department.</h4>

<p>Here you could use either of <code>.annotate</code> or <code>.aggregate</code>,</p>

<pre><code>Department.objects.filter(dept_name='Sales').values('dept_name').annotate(Count('employee'))
Department.objects.filter(dept_name='Sales').aggregate(Count('employee'))
</code></pre>

<p>If you see the SQLs, you will see that <code>.annotate</code> did a <code>group by</code>, while the <code>.aggregate</code>
did not, but as there was only one row, <code>group by</code> had no effect.</p>

<h4>Find the total number of employees, per department, per level</h4>

<p>This time, we can not annotate either Department model, or the Level model, as we
need to <code>group by</code> both department and level. So we will annotate on Employee</p>

<pre><code>Employee.objects.values('department__dept_name', 'level__level_name').annotate(Count('id'))
</code></pre>

<p>This leads to the sql,</p>

<pre><code>SELECT "hrms_department"."dept_name", "hrms_level"."level_name", COUNT("hrms_employee"."id") AS "id__count" FROM "hrms_employee" INNER JOIN "hrms_department" ON ("hrms_employee"."department_id" = "hrms_department"."id") INNER JOIN "hrms_level" ON ("hrms_employee"."level_id" = "hrms_level"."id") GROUP BY "hrms_department"."dept_name", "hrms_level"."level_name
</code></pre>

<h4>Which combination of Employee and Deparments employes the most people</h4>

<p>We can order on the annotated fields, so the last query is modified to,</p>

<pre><code>Employee.objects.values('department__dept_name', 'level__level_name').annotate(employee_count = Count('id')).order_by('-employee_count')[:1]
</code></pre>

<h4>Which employee name is the most common.</h4>

<p>We can want to <code>group by emp_name</code>, so <code>emp_name</code> is added to values. After that we order on the annotated field
and get the first element, to get the most common name.</p>

<p><code>Employee.objects.values('emp_name').annotate(name_count=Count('id')).order_by('-name_count')[:1]</code></p>

<hr />

<p>This was a overview of how django annotations work. These remove a whole class of queries for which
you had to use custom sql queries in the past.</p>

<hr />

<h3>Resources</h3>

<ol>
<li><a href="http://github.com/uswaretech/Shiny-New-Django-1.1/tree/master">Source on Github</a></li>
<li><a href="http://dl.getdropbox.com/u/271935/djaggregations/bata.db">sqlite file for this model to test</a></li>
<li><a href="http://docs.djangoproject.com/en/dev/topics/db/aggregation/">Aggregation on Django docs</a></li>
</ol>

<hr />

<p>Want to build a Django app? <a href="http://uswaretech.com/contact/">Talk to us</a></p>


<p>Related posts:<ol><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/2008/04/new-tutorial-building-a-search-engine-with-appengine-and-yahoo/' rel='bookmark' title='Permanent Link: New tutorial &#8211; Building a search engine with Appengine and Yahoo'>New tutorial &#8211; Building a search engine with Appengine and Yahoo</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/2009/08/django-aggregation-tutorial/feed/</wfw:commentRss>
		<slash:comments>28</slash:comments>
		</item>
		<item>
		<title>On Captcha</title>
		<link>http://uswaretech.com/blog/2009/07/on-captcha/</link>
		<comments>http://uswaretech.com/blog/2009/07/on-captcha/#comments</comments>
		<pubDate>Thu, 16 Jul 2009 08:35:35 +0000</pubDate>
		<dc:creator>shabda</dc:creator>
				<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://uswaretech.com/blog/?p=49</guid>
		<description><![CDATA[When building public facing websites, spam is a real problem. Captcha has been teated as the first line of defence aginst this problem. If you must use captcha, here are some best practices working with them. Can you do without one? A lot of places captcha&#8217;s are put to filter spam in user generated comment. [...]


Related posts:<ol><li><a href='http://uswaretech.com/blog/2008/04/parable-of-the-captcha-the-futility-of-fighting-automated-spam-with-automated-methods/' rel='bookmark' title='Permanent Link: Parable of the Captcha &#8211; The futility of fighting automated spam with automated methods.'>Parable of the Captcha &#8211; The futility of fighting automated spam with automated methods.</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p></p><p>When building public facing websites, spam is a real problem. Captcha has been teated as the first line of defence aginst this problem. If you must use captcha, here are some best practices working with them.</p>

<h3>Can you do without one?</h3>

<p>A lot of places captcha&#8217;s are put to filter spam in user generated comment. One of the largest sources of UGC is comments on wordpress blogs. They do not use a captcha, and instead pass all comments through Akismet to verify which comments are spam, and reject the spams. In many cases, such a system would work for you.</p>

<h3>Can you use a simpler alternative?</h3>

<p>Unless you run a site with millions of monthly users, the spammers are not going to write a bot specifically for youur site. So if you have a text question asking &#8220;what is 2 + 2&#8243;, the bots are not going to get past that, as the question is unique to your site. Of course, gmail/yahoo can not use this approach, as bots get written for them specifically, but for you site it might.</p>

<p>This proposed approach has been called <a href="http://dmytry.pandromeda.com/texts/captcha_and_saptcha.html">SAPTCHA</a> and anecdotal evidence suggests that it works very well in practice.</p>

<h3>Prefer recaptcha</h3>

<p><a href="http://recaptcha.net/">Recaptcha</a> is an existing implementation of captcha, which allows you to plug in a captcha system, to your existing pages. Using this over home grown captcha&#8217;s offers advantages like</p>

<ol>
<li>Its is battle tested, in being both secure against bots and having a level of usability.</li>
<li>It automatically provides and alternate means of validation. Which brings us to our third point.</li>
</ol>

<h3>Provide alternate means of validation to visually impaired people.</h3>

<p>This might be in the form of an audio captcha, an option to email the administrator.</p>

<h3>Do captcha validation only once</h3>

<p>This seems so obvious, and yet many sites require you to complete captcha multiple times, in case of any error in the form. Once an user has completed captcha, the form must be displayed without captcha in case of errors.</p>

<hr />

<p>If you use Django, these are already very easy to use with existing apps.</p>

<ol>
<li><a href="http://www.djangosnippets.org/snippets/433/">Django recaotcha</a></li>
<li><a href="http://www.djangosnippets.org/snippets/1255/">Django akismet</a></li>
<li><a href="http://defensio.com/downloads/python/">Python defensio</a></li>
</ol>

<hr />

<p>You should follow me on twitter <a href="http://twitter.com/uswaretech">here</a><a href="http://dustincurtis.com/you_should_follow_me_on_twitter.html">.</a></p>


<p>Related posts:<ol><li><a href='http://uswaretech.com/blog/2008/04/parable-of-the-captcha-the-futility-of-fighting-automated-spam-with-automated-methods/' rel='bookmark' title='Permanent Link: Parable of the Captcha &#8211; The futility of fighting automated spam with automated methods.'>Parable of the Captcha &#8211; The futility of fighting automated spam with automated methods.</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://uswaretech.com/blog/2009/07/on-captcha/feed/</wfw:commentRss>
		<slash:comments>1</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>Django design patterns</title>
		<link>http://uswaretech.com/blog/2009/07/django-design-patterns/</link>
		<comments>http://uswaretech.com/blog/2009/07/django-design-patterns/#comments</comments>
		<pubDate>Fri, 03 Jul 2009 14:11:46 +0000</pubDate>
		<dc:creator>shabda</dc:creator>
				<category><![CDATA[book]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://uswaretech.com/blog/?p=605</guid>
		<description><![CDATA[This is announcement about our new work, Django design patterns, a ebook about, well, Django design patterns. (Well imagine that!). Here is the readme copied from there. [Edit] Syntax highlighting and indentation preservation were totally brroken. Fixed now. Django design patterns is a book about commonly occuring patterns in Django. Not patterns in Gof sense, [...]


Related posts:<ol><li><a href='http://uswaretech.com/blog/2009/11/django-gotchas/' rel='bookmark' title='Permanent Link: Django gotchas'>Django gotchas</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p></p><p>This is announcement about our new work, <a href="http://djangodesignpatterns.uswaretech.net/">Django design patterns</a>, a ebook about, well, Django design patterns. (Well imagine that!). Here is the readme copied from there.</p>

<hr />

<p>[Edit] Syntax highlighting and indentation preservation were totally brroken. Fixed now.</p>

<hr />

<p>Django design patterns is a book about commonly occuring patterns in Django. Not
patterns in Gof sense, but patterns in the sense, we work this way, and it works
for us. For us it is a ~pattern of work~ sense.</p>

<p>At this point this is just a lot of brain dump from us.</p>

<p>The latest sources are always available from

http://github.com/uswaretech/django-design-patterns/tree/master

and latest html from http://djangodesignpatterns.uswaretech.net/</p>

<hr />

<p>Please leave errata, feedback, critique as comments here.</p>

<hr />

<p>This is still very much a work in progress, released in the spirit of release early, release often. <a href="http://djangodesignpatterns.uswaretech.net/">Click here</a> to get it, or <a href="http://github.com/uswaretech/django-design-patterns/tree/master">fork it on Github</a></p>


<p>Related posts:<ol><li><a href='http://uswaretech.com/blog/2009/11/django-gotchas/' rel='bookmark' title='Permanent Link: Django gotchas'>Django gotchas</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://uswaretech.com/blog/2009/07/django-design-patterns/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Remote debugging &#8211; debugging pesky server only bugs</title>
		<link>http://uswaretech.com/blog/2009/07/remote-debugging-debugging-pesky-server-only-bugs/</link>
		<comments>http://uswaretech.com/blog/2009/07/remote-debugging-debugging-pesky-server-only-bugs/#comments</comments>
		<pubDate>Thu, 02 Jul 2009 18:07:02 +0000</pubDate>
		<dc:creator>shabda</dc:creator>
				<category><![CDATA[django]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://uswaretech.com/blog/?p=600</guid>
		<description><![CDATA[Here is a quick tip. (Obvious if you work with Django for any length of time, but I have seen a few people who are not aware) You can put debug trace import pdb; pdb.set_trace() in your code, and put it on the server. When you access this view from your local browser, the debug [...]


Related posts:<ol><li><a href='http://uswaretech.com/blog/2008/04/using-appengine-with-django-why-it-is-pretty-much-unusable/' rel='bookmark' title='Permanent Link: Using Appengine with Django, why it is pretty much unusable'>Using Appengine with Django, why it is pretty much unusable</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p></p><p>Here is a quick tip. (Obvious if you work with Django for any length of time, but I have seen a few people who are not aware)</p>

<p>You can put debug trace <code>import pdb; pdb.set_trace()</code> in your code, and put it on the server. When you access this view from your local browser, the debug is still hit and you have a debug shell on your server where you can step through. (Obviously this works only if you ran the code via <code>manage.py runserver</code>. But <code>manage.py runserver</code> start the server to listen only on local connections. If you want to access remotely you need to run as,</p>

<pre><code>python manage.py runserver 0.0.0.0:8000
</code></pre>

<p>Edit: As <a href="http://tactful.co.nz/">SmileyChris</a> commented, a faster way is,</p>

<pre><code>python manage.py runserver 0:8000
</code></pre>

<p>The <code>0.0.0.0</code> implies that remote connections are possible.</p>

<p>For me, this has been a lifesaver against those pesky bugs which show themselves only on the server, but not on the local machine.</p>


<p>Related posts:<ol><li><a href='http://uswaretech.com/blog/2008/04/using-appengine-with-django-why-it-is-pretty-much-unusable/' rel='bookmark' title='Permanent Link: Using Appengine with Django, why it is pretty much unusable'>Using Appengine with Django, why it is pretty much unusable</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://uswaretech.com/blog/2009/07/remote-debugging-debugging-pesky-server-only-bugs/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
