<?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; django</title>
	<atom:link href="http://uswaretech.com/blog/category/django/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>Rails and Django commands : comparison  and conversion</title>
		<link>http://uswaretech.com/blog/2010/03/rails-and-django-commands-comparison-and-conversion/</link>
		<comments>http://uswaretech.com/blog/2010/03/rails-and-django-commands-comparison-and-conversion/#comments</comments>
		<pubDate>Sat, 20 Mar 2010 13:05:30 +0000</pubDate>
		<dc:creator>shabda</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[rails]]></category>

		<guid isPermaLink="false">http://uswaretech.com/blog/?p=936</guid>
		<description><![CDATA[The most commonly used Rails commands and their Django equivalents Rails Django rails console manage.py shell rails server manage.py runserver rake None rails generate None rails dbconsole manage.py dbshell rails app_name django-admin.py startproject/manage.py startapp rake db:create manage.py syncdb The salient points to note are, Django has all commands via manage.py, Rails has it broken into [...]


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/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>The most commonly used Rails commands and their Django equivalents</p>

<table>
<thead>
<tr>
  <th>Rails</th>
  <th>Django</th>
</tr>
</thead>
<tbody>
<tr>
  <td>rails console</td>
  <td>manage.py shell</td>
</tr>
<tr>
  <td>rails server</td>
  <td>manage.py runserver</td>
</tr>
<tr>
  <td>rake</td>
  <td>None</td>
</tr>
<tr>
  <td>rails generate</td>
  <td>None</td>
</tr>
<tr>
  <td>rails dbconsole</td>
  <td>manage.py dbshell</td>
</tr>
<tr>
  <td>rails app_name</td>
  <td>django-admin.py startproject/manage.py startapp</td>
</tr>
<tr>
  <td>rake db:create</td>
  <td>manage.py syncdb</td>
</tr>
</tbody>
</table>

<p>The salient points to note are,</p>

<ol>
<li>Django has all commands via <code>manage.py</code>, Rails has it broken into <code>rails</code> and <code>rake</code>.</li>
<li>Overall there are more Rails+Rake commands available than Django commands</li>
<li>There is no one to one mapping between Rails and Django commands.
Eg. There are no equivalent to rake doc:* or rake notes in Django.</li>
</ol>

<p>Similarly there is no equivalent to <code>manage.py createsuperuser</code> in rails.</p>

<h4>References</h4>

<p><a href="http://docs.djangoproject.com/en/dev/ref/django-admin/">http://docs.djangoproject.com/en/dev/ref/django-admin/</a>
<a href="http://guides.rails.info/command_line.html">http://guides.rails.info/command_line.html</a>
<a href="http://github.com/uswaretech/Acts-as-Django/blob/master/commands.markdown">http://github.com/uswaretech/Acts-as-Django/blob/master/commands.markdown</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/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/2010/03/rails-and-django-commands-comparison-and-conversion/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<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>WordPress and Django: best buddies</title>
		<link>http://uswaretech.com/blog/2010/01/wordpress-and-django-best-buddies/</link>
		<comments>http://uswaretech.com/blog/2010/01/wordpress-and-django-best-buddies/#comments</comments>
		<pubDate>Sun, 17 Jan 2010 14:25:29 +0000</pubDate>
		<dc:creator>shabda</dc:creator>
				<category><![CDATA[about]]></category>
		<category><![CDATA[apps]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://uswaretech.com/blog/?p=902</guid>
		<description><![CDATA[Summary: How to integrate a non Django database system in your Django code, using WordPress as example. The completed code is available at github or you can see some screnshots Though there are quite a few good Django blog applications, our blog is based on WordPress. A number of plugin&#8217;s make moving to a Django [...]


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/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>
</ol>]]></description>
			<content:encoded><![CDATA[<p></p><p>Summary:
How to integrate a non Django database system in your Django code, using WordPress
as example. <a href="http://github.com/uswaretech/django-wordpress">The completed code is available at github</a> or you can <a href="#screenshots_wp">see some screnshots</a></p>

<hr />

<p>Though there are quite a <a href="http://github.com/montylounge/django-mingus">few good</a> <a href="http://byteflow.su/">Django blog</a> applications, our blog is based on
<a href="http://wordpress.org/">WordPress</a>. A <a href="http://mitcho.com/code/yarpp/">number</a> <a href="http://diythemes.com/">of</a> <a href="http://www.backtype.com/">plugin&#8217;s</a>
make moving to a Django based app a bad decision
for us, and not in the spirit of &#8220;best tools for the job&#8221;.</p>

<p>We moved the other way, and decided to use <a href="http://github.com/uswaretech/django-wordpress">Django to admin the
WordPress database</a>. The completed code is available on <a href="http://github.com/uswaretech/django-wordpress">Github</a></p>

<p>It is not too hard, with the the builtin Django commands. Django provides the
<a href="http://www.djangobook.com/en/1.0/chapter16/"><code>inspectdb</code></a> command which allows you to build your models.py from an existing
non Django database.</p>

<p>Here we will see the steps followed for WordPress, but it would be about the same for all
systems.</p>

<h5>Take a back up of wordpress</h5>

<pre><code>mysqldump -u wordpress_user -p --database wordpress_database &gt; data.sql
</code></pre>

<h5>Create a new project, and set its settings to use the WordPress database.</h5>

<pre><code>    DATABASE_ENGINE = 'mysql'           # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
    DATABASE_NAME = ''             # Or path to database file if using sqlite3.
    DATABASE_USER = ''             # Not used with sqlite3.
    DATABASE_PASSWORD = ''         # Not used with sqlite3.
    DATABASE_HOST = ''             # Set to empty string for localhost. Not used with sqlite3.
    DATABASE_PORT = ''             # Set to empty string for default. Not used with sqlite3.
</code></pre>

<h5>Get the initial models.py</h5>

<pre><code>./manage.py inspectdb &gt; models.py
</code></pre>

<p>This will create all the database tables in a form Django can understand. Here is what this command creates for a
my WordPress installation with the YARPP plugin. <a href="http://gist.github.com/278962">http://gist.github.com/278962</a></p>

<h5>Create a new app and put this models.py there.</h5>

<p>With this done, you can treat the non Django part as a
standalone application. Since WordPress appends all its table with <code>wp_</code> prefix,
we name this applications <code>wp</code> to maintain table name compatibility with Django naming
conventions.</p>

<p>You will notice that all models have the <code>db_table</code> populated, so we can rename tables, without changes to the database.</p>

<h5>Differences between WordPress and Django style naming.</h5>

<p>At this point you will notice some differences in how Django names things (in a
best practice sort of way), and how WordPress does it.</p>

<p>a. Django table and model class name are (generally) singular. eg <code>class Post(models.Models)</code> leads to table <code>app_post</code>.
WordPress tables are (most of them) named plural eg <code>wp_posts</code>.</p>

<p>b. Django attributes are generally named without the table name part. Eg</p>

<pre><code>class Comment(models.Model):
    author_name = models.TextField()
    content = models.TextField()
</code></pre>

<p>WordPress is explicit here and includes the table prefix with attributes.</p>

<pre><code>mysql&gt; desc wp_comments;
+----------------------+---------------------+------+-----+---------------------+----------------+
| Field                | Type                | Null | Key | Default             | Extra          |
+----------------------+---------------------+------+-----+---------------------+----------------+
| comment_ID           | bigint(20) unsigned | NO   | PRI | NULL                | auto_increment | 
| comment_post_ID      | bigint(20) unsigned | NO   | MUL | 0                   |                | 
| comment_author       | tinytext            | NO   |     | NULL                |                | 
| comment_author_email | varchar(100)        | NO   |     |                     |                | 

.....
</code></pre>

<p>I believe this is due to the way you would generally be using the code. In Django you would do
<code>comment.author</code> where being explicit doesn&#8217;t add any value, while in WordPress, you would use,
<code>select comment_author, post_title ... from wp_comment, wp_post ... where join</code>, where being explicit
is useful.</p>

<p>You can decouple the Django and database names by using the <code>db_table</code> and <code>db_column</code> attributes.
We choose to rename the Class names to match Django conventions while we let the column names remain the same.</p>

<h5>Add Admin and other Django niceties.</h5>

<p>WordPress doesn&#8217;t (seem to) have foreign key constraints setup correctly, and
uses  <code>bigint(20) unsigned</code> without foreign key constraints to refer to referred entities.
This means Django creates all ForeignKeys as IntegerFields.</p>

<p>Modify them to use ForeignKey instead. Also add <code>__unicode__</code>, to your classes.</p>

<p>Add an <code>admin.py</code> to register all your classes.</p>

<p>And you are done! Now you can access, and work with your WordPress data inside Django
and Django admin.</p>

<hr />

<p>There are a few more things which will allow a easier WordPress setup.</p>

<h5>Create template tags to show the latest posts and comments.</h5>

<pre><code>@register.inclusion_tag("wp/recent_posts.html")
def show_posts(num_comments):
    return {"posts": Post.objects.filter(post_type="post", post_status="publish").order_by("-post_date")[:num_comments]}
</code></pre>

<p>So you can see that there is nothing WordPress specific we need too do here.</p>

<h5>Create a better admin.</h5>

<pre><code>Add ModelAdmin to generally used models.
</code></pre>

<h5>Allows accessing attributes via the Django style names.</h5>

<p>If you override <code>__getattr__</code>, you can access
the attributes via other names. Eg in the current setup you need to do <code>comment.comment_content</code>, <code>comment.comment_author</code> etc,
while we would like to do <code>comment.content</code>  and <code>comment.author</code> as a shortcut.</p>

<pre><code>class WordPressModel(object):    
    def __getattr__(self, v):
        if v in self.__dict__:
            return self.__dict__[v]
        else:
            new_v = "%s_%s" % (self.__class__.__name__.lower(),  v)
            if new_v in self.__dict__:
                return self.__dict__[new_v]
            else:
                raise AttributeError
</code></pre>

<p>It is highly debatable whether this is a good idea <img src='http://uswaretech.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> , but it is too convenient right now not to test this method out.</p>

<p><a name="screenshots_wp" />
Here are some screenshots.</p>

<p><img alt="" src="http://uswaretech.com/dump/screenshots/screenshot_010.png" title="WordPress django admin" class="alignnone" width="600" /></p>

<p><img alt="" src="http://uswaretech.com/dump/screenshots/screenshot_011.png" title="WordPress django admin" class="alignnone" width="600" /></p>

<hr />

<p><a href="http://feeds.feedburner.com/uswarearticles">Do you subscribe to our feed</a>? We recently made a full text feed available, so if you are using the old feed, you should change it. <a href="http://feeds.feedburner.com/uswarearticles">Subscribe now</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/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>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://uswaretech.com/blog/2010/01/wordpress-and-django-best-buddies/feed/</wfw:commentRss>
		<slash:comments>39</slash:comments>
		</item>
		<item>
		<title>Doing things with Django forms</title>
		<link>http://uswaretech.com/blog/2010/01/doing-things-with-django-forms/</link>
		<comments>http://uswaretech.com/blog/2010/01/doing-things-with-django-forms/#comments</comments>
		<pubDate>Thu, 14 Jan 2010 11:26:18 +0000</pubDate>
		<dc:creator>shabda</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[forms]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://uswaretech.com/blog/?p=881</guid>
		<description><![CDATA[Forms are one of the best features of Django. (After models, admin, url routing etc ). Here is a quick tutorial describing how to do things with Django forms. Basic form Prob. You want to show a form, validate it and display it. Ans. Create a simple form. class UserForm(forms.Form): username = forms.CharField() joined_on = [...]


Related posts:<ol><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/2008/04/five-things-i-hate-about-django/' rel='bookmark' title='Permanent Link: Five Things I Hate About Django.'>Five Things I Hate About Django.</a></li>
<li><a href='http://uswaretech.com/blog/2009/04/develop-twitter-api-application-in-django-and-deploy-on-google-app-engine/' rel='bookmark' title='Permanent Link: Develop Twitter API application in django and deploy on Google App Engine'>Develop Twitter API application in django and deploy on Google App Engine</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p></p><p>Forms are one of the best features of Django. (After models, admin, url routing etc <img src='http://uswaretech.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  ). Here is a quick tutorial describing how to do things with Django forms.</p>

<ol>
<li>Basic form</li>
</ol>

<p>Prob. You want to show a form, validate it and display it.</p>

<p>Ans. Create a simple form.</p>

<pre><code>class UserForm(forms.Form):
    username = forms.CharField()
    joined_on = forms.DateField()
</code></pre>

<p>This wil take care that the form is displayed with two text field,
and a value for them are filled in, and the second field has correct formatting for a date.</p>

<p>2.</p>

<p>Prob. Create a form which has values populated depending upon a runtime value,
eg you might want to show only the values corresponding to the current subdomain.</p>

<p>Ans. Create a form with an custom <code>__init__</code>.</p>

<pre><code>class UserForm(forms.Form):
    username = forms.CharField()
    plan = forms.ModelChoiceField(queryset = Plan.objects.none())

    def __init__(self, subdomain, *args, **kwargs):
        self.default_username = default_username
        super(UserForm, self).__init__(*args, **kwargs)
        self.fields['plan'].queryset = Plan.objects.filter(subdomain = subdomain)
</code></pre>

<p>Here in the <code>__init__</code> we are overriding the default queryset on field <code>plan</code>. Any of the attributes can similarly be overridden.</p>

<p>However the <code>self.fields</code> is populated only after <code>super(UserForm, self).__init__(*args, **kwargs)</code> is called.</p>

<p>3.</p>

<p>Prob. The same form is used in multiple views, and handles the <code>cleaned_data</code> similarly.</p>

<p>Ans. Create a form with a custom .save()</p>

<pre><code>class UserForm(forms.Form):
    username = forms.CharField()

    def save(self):
        data = self.cleaned_data
        user = User.objects.create(username = data['username'])
        #create a profile
        UserProfile.objects.create(user = user, ...some more data...)
</code></pre>

<p>You could have called this method anything, but this is generally called save, to maintain similarity with <code>ModelForm</code></p>

<p>4.</p>

<p>Prob. You need to create a form with fields which have custom validations.</p>

<p>Ans. Create a form with custom clean_fieldname</p>

<pre><code>class UserForm(forms.Form):
    username = forms.CharField()

    def clean_username(self):
        data = self.cleaned_data
        try:
            User.objects.get(username = data['username'])
        except User.DoesNotExist:
            return data['username']
        raise forms.ValidationError('This username is already taken.')
</code></pre>

<p>Here we can validate that the usernames are not repeated.</p>

<p>5.</p>

<p>Prob. You want to create a field which has cross field validations.</p>

<p>Ans. Create a field with a .clean</p>

<pre><code>class UserForm(forms.Form):
    username = forms.CharField()

    password1 = forms.PasswordField()
    password2 = forms.PasswordField()

    def clean(self):
        data = self.cleaned_data
        if "password1" in data and "password2" in data and data["password1"] != data["password2"]:
            raise forms.ValudationError("Passwords must be same")
</code></pre>

<p>6.</p>

<p>Problem.</p>

<p>You need a form the fields of which depends on some value in the database.
Eg. The field to be shown are customisable per user.</p>

<p>Create a form dynamically</p>

<pre><code>def get_user_form_for_user(user):
        class UserForm(forms.Form):
            username = forms.CharField()
            fields = user.get_profile().all_field()
            #Use field to find what to show.
</code></pre>

<p><a href="http://uswaretech.com/blog/2008/10/dynamic-forms-with-django/">This post provides much more details</a></p>

<p>7.</p>

<p>Prob. You need to create a Html form which writes to multiple Django models.</p>

<p>Ans. Django forms are not a one to one mapping to Html forms.</p>

<pre><code>#in forms.py
class UserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ["username", "email"]

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile

#in views.py
def add_user(request):
    ...
    if request.method == "POST":
        uform = UserForm(data = request.POST)
        pform = UserProfileForm(data = request.POST)
        if uform.is_valid() and pform.is_valid():
            user = uform.save()
            profile = pform.save(commit = False)
            profile.user = user
            profile.save()
            ....
    ...

#in template
&lt;form method="post"&gt;
    {{ uform.as_p }}
    {{ pform.as_p }}
    &lt;input type="submit" ...&gt;
&lt;/form&gt;
</code></pre>

<p>8.</p>

<p>Prob. You want to use multiple forms of same type on one page.</p>

<p>Ans.</p>

<p>a. If you want a datagrid style ui, use formset.</p>

<pre><code>from django.forms.formsets import formset_factory
forms = formset_factory(UserForm, extra = 4)
#
</code></pre>

<p><a href="http://docs.djangoproject.com/en/dev/topics/forms/formsets/">Formsets are described much more comprehensively here</a></p>

<p>b. If you do not need a datagrid style ui, use <code>prefix</code> argument to forms.</p>

<pre><code>Eg. you have a survey app, and you want a page with all questions from that survey displayed.

#IN views.py
def survey(request, survey_slug)
    ...
    questions = survey.questions.all()
    question_forms = []
    for question in questions:
        qform = QuestionForm(question=question, prefix = question.slug)
        question_forms.append(qform)
        ...
    if request.method == "POST":
        for question in questions:
            qform = QuestionForm(question=question, prefix = question.slug, data = request.POST)
        #Validate and do save action
        ...
    ...
</code></pre>

<hr />

<p><a href="http://feeds.feedburner.com/uswarearticles">Do you subscribe to our feed</a>? We recently made a full text feed available, so if you are using the old feed, you should change it. <a href="http://feeds.feedburner.com/uswarearticles">Subscribe now</a>.</p>


<p>Related posts:<ol><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/2008/04/five-things-i-hate-about-django/' rel='bookmark' title='Permanent Link: Five Things I Hate About Django.'>Five Things I Hate About Django.</a></li>
<li><a href='http://uswaretech.com/blog/2009/04/develop-twitter-api-application-in-django-and-deploy-on-google-app-engine/' rel='bookmark' title='Permanent Link: Develop Twitter API application in django and deploy on Google App Engine'>Develop Twitter API application in django and deploy on Google App Engine</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://uswaretech.com/blog/2010/01/doing-things-with-django-forms/feed/</wfw:commentRss>
		<slash:comments>41</slash:comments>
		</item>
		<item>
		<title>django-forum</title>
		<link>http://uswaretech.com/blog/2010/01/django-forum/</link>
		<comments>http://uswaretech.com/blog/2010/01/django-forum/#comments</comments>
		<pubDate>Thu, 07 Jan 2010 11:19:03 +0000</pubDate>
		<dc:creator>shabda</dc:creator>
				<category><![CDATA[apps]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[utilities]]></category>

		<guid isPermaLink="false">http://uswaretech.com/blog/?p=856</guid>
		<description><![CDATA[twitter ready version: We have released a Django forum application, with some cool features not in any other Django based forum. You can get it here or see it in action. blog version There are quite a few Django based forum applications, so why another? Its a bit of a rhetorical question, as the answer [...]


No related posts.]]></description>
			<content:encoded><![CDATA[<p></p><h3>twitter ready version:</h3>

<p>We have released a <a href="http://uswaretech.com/forum/">Django forum</a> application, with some cool features not in any other Django based forum. <a href="http://github.com/uswaretech/Dinette">You can get it here</a> or <a href="http://uswaretech.com/forum/">see it in action</a>.</p>

<h3>blog version</h3>

<p>There are quite a few <a href="http://code.djangoproject.com/wiki/ForumAppsComparison">Django based forum applications</a>, so why another? Its a bit of a rhetorical question,  as the answer is &#8220;none of them met my needs exactly, so we created my own&#8221;, as you might expect.</p>

<p>Without further ado here is a list of features. It is available on <a href="http://uswaretech.com/forum/">uswaretech.com/forum/</a>.</p>

<ul>
<li>Based on, inspired by and ripped from <a href="http://punbb.informer.com/">PunBB</a>. (Thanks!)</li>
<li>PunBB like 3 phased hierarchy [Forum]->Subforum->Topic->Post</li>
<li>Tightly integrated with <a href="http://github.com/uswaretech/Django-Socialauth">Socialauth</a>. (Screenshots)</li>
<li><a href="http://www.gravatar.com/">Gravatar</a> support</li>
<li>Moderation features (Close, stikify, make announcement etc.)</li>
<li>Ajax based posting</li>
</ul>

<p>We are starting our forums based on this app, so we plan to be supporting and developing this for foreseeable future. <a href="http://github.com/uswaretech/Dinette">Fork this on Github</a> or <a href="http://uswaretech.com/forum/">check this out now</a>.</p>

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

<h3>Screenshots</h3>

<p>Main page</p>

<p><a href="http://uswaretech.com/dump/screenshots/screenshot_007.png"><img alt="" src="http://uswaretech.com/dump/screenshots/screenshot_007.png" title="Dinette screenshot" class="alignnone" width="640" height="420" /></a> <br /> <br /></p>

<p>Post page</p>

<p><a href="http://uswaretech.com/dump/screenshots/screenshot_008.png"><img alt="" src="http://uswaretech.com/dump/screenshots/screenshot_008.png" title="Dinette screenshot" class="alignnone"  width="640" height="420" /></a> <br /> <br /></p>

<p>Login Page</p>

<p><a href="http://uswaretech.com/dump/screenshots/screenshot_009.png"><img alt="" src="http://uswaretech.com/dump/screenshots/screenshot_009.png" title="Dinette screenshot" class="alignnone"  width="640" height="420" /></a> <br /> <br /></p>

<hr />

<p>We build amazing web apps. <a href="http://uswaretech.com/contact/">Contact us</a></p>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://uswaretech.com/blog/2010/01/django-forum/feed/</wfw:commentRss>
		<slash:comments>57</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>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 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>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>
	</channel>
</rss>
