<?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</title>
	<atom:link href="http://uswaretech.com/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://uswaretech.com/blog</link>
	<description>Building Amazing Webapps</description>
	<lastBuildDate>Mon, 18 Jan 2010 15:11:52 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<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 you to build [...]


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/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/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>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/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/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/2010/01/django-models-tutorial/feed/</wfw:commentRss>
		<slash:comments>13</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 based app a bad decision
for [...]


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>
</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>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://uswaretech.com/blog/2010/01/wordpress-and-django-best-buddies/feed/</wfw:commentRss>
		<slash:comments>34</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()
  [...]


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>40</slash:comments>
		</item>
		<item>
		<title>Tools of Pro Django developer &#8211; aka What powers dinette and almost every app we write.</title>
		<link>http://uswaretech.com/blog/2010/01/tools-of-pro-django-developer/</link>
		<comments>http://uswaretech.com/blog/2010/01/tools-of-pro-django-developer/#comments</comments>
		<pubDate>Wed, 13 Jan 2010 12:32:11 +0000</pubDate>
		<dc:creator>shabda</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[django]]></category>

		<guid isPermaLink="false">http://uswaretech.com/blog/?p=870</guid>
		<description><![CDATA[There are some tools and apps which we use with almost all apps we write, and in particular which,
we used for dinette. Here they are broken into useful during development,
and (also) useful post development.

During Development


Ipython and ipdb
South
Django test utils
Django extensions
Django debug toolbar


Ipython and ipdb

Ipython is a enhanced shell for python. Ipdb similarly add extra capacity [...]


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>22</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 is &#8220;none [...]


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>46</slash:comments>
		</item>
		<item>
		<title>Django-buzz</title>
		<link>http://uswaretech.com/blog/2009/12/django-buzz/</link>
		<comments>http://uswaretech.com/blog/2009/12/django-buzz/#comments</comments>
		<pubDate>Sat, 12 Dec 2009 21:31:42 +0000</pubDate>
		<dc:creator>shabda</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://uswaretech.com/blog/?p=845</guid>
		<description><![CDATA[We have updated the Django popular stories widget, which powers the widget in the side bar. It is now on Github.

Earlier the code used was hardcoded to only find Django stories, but now you can create arbitary topics from admin.

Get the code and create the widgets on your servers, (or let us know, and we [...]


Related posts:<ol><li><a href='http://uswaretech.com/blog/2009/02/django-popular-stories-widget/' rel='bookmark' title='Permanent Link: Django popular stories Widget'>Django popular stories Widget</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p></p><p>We have updated the <a href="http://uswaretech.com/blog/2009/02/django-popular-stories-widget/">Django popular stories widget</a>, which powers the widget in the side bar. <a href="http://github.com/uswaretech/django-buzz">It is now on Github</a>.</p>

<p>Earlier the code used was hardcoded to only find Django stories, but now you can create arbitary topics from admin.</p>

<p>Get the code and create the widgets on your servers, (or let us know, and we will create it here if it is interesting). We created three we want to track. <a href="http://uswaretech.com/pystories/databases/">Databases</a>, <a href="http://uswaretech.com/pystories/python/">Python</a> and <a href="http://uswaretech.com/pystories/javascript/">Javascript</a></p>

<h3><a href="http://uswaretech.com/pystories/databases/">Databases</a></h3>

<iframe src ="http://uswaretech.com/pystories/widget/databases/"   id="doloto_iframe"  width="250px" height="525px"  frameborder=0  border=0    style = "padding-top : 5px"> </iframe>

<h3><a href="http://uswaretech.com/pystories/python/">Python</a></h3>

<iframe src ="http://uswaretech.com/pystories/widget/python/"   id="doloto_iframe"  width="250px" height="525px"  frameborder=0  border=0    style = "padding-top : 5px"> </iframe>

<h3><a href="http://uswaretech.com/pystories/javascript/">Javascript</a></h3>

<iframe src ="http://uswaretech.com/pystories/widget/javascript/"   id="doloto_iframe"  width="250px" height="525px"  frameborder=0  border=0    style = "padding-top : 5px"> </iframe>

<hr />

<p>We build amazing web apps. <a href="/contact/">Talk to us</a> to discuss what we can do for you.</p>


<p>Related posts:<ol><li><a href='http://uswaretech.com/blog/2009/02/django-popular-stories-widget/' rel='bookmark' title='Permanent Link: Django popular stories Widget'>Django popular stories Widget</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://uswaretech.com/blog/2009/12/django-buzz/feed/</wfw:commentRss>
		<slash:comments>4</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 the [...]


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>59</slash:comments>
		</item>
		<item>
		<title>Foss.in 2009: The best foss.in. Ever.</title>
		<link>http://uswaretech.com/blog/2009/12/foss-in-2009-the-best-foss-in-ever/</link>
		<comments>http://uswaretech.com/blog/2009/12/foss-in-2009-the-best-foss-in-ever/#comments</comments>
		<pubDate>Thu, 10 Dec 2009 17:28:31 +0000</pubDate>
		<dc:creator>lakshman</dc:creator>
				<category><![CDATA[India]]></category>
		<category><![CDATA[meta]]></category>

		<guid isPermaLink="false">http://uswaretech.com/blog/?p=809</guid>
		<description><![CDATA[There are technology conferences, and then there are gatherings of passionate technology enthusiasts. You will most likely not know what I am talking about, unless you saw that someone wrote a software for controlling a toy-car, using it&#8217;s blue tooth module, from an Nokia phone, at the event. You will most likely not know what [...]


Related posts:<ol><li><a href='http://uswaretech.com/blog/2009/10/pycon-india-2009/' rel='bookmark' title='Permanent Link: Pycon India 2009 : A Review'>Pycon India 2009 : A Review</a></li>
<li><a href='http://uswaretech.com/blog/2008/08/what-is-usware-technologies/' rel='bookmark' title='Permanent Link: What is Usware Technologies?'>What is Usware Technologies?</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p></p><p>There are technology conferences, and then there are gatherings of passionate technology enthusiasts. You will most likely not know what I am talking about, unless you saw that someone wrote a software for controlling a toy-car, using it&#8217;s blue tooth module, from an Nokia phone, at the event. You will most likely not know what I am talking about, unless you were at Nimhans Convention center at Bangalore between 1st to 5th December 2009.</p>

<p><img src="http://farm3.static.flickr.com/2507/4153869960_fcce742e42_m_d.jpg" alt="nimhans" /></p>

<p><img src="http://farm5.static.flickr.com/4001/4160152863_014ee73c03_m_d.jpg" alt="hardware hack" /></p>

<p><a href="http://foss.in/">Foss.in</a> had its beginnings <a href="http://en.wikipedia.org/wiki/FOSS.IN#History">10 years ago</a>, as linux bangalore, whose objective was the popularize free and open source software to local Indians. From there, from being an end user Linux evangelizing conference to being a developer focused event, where the developers are the super stars, where even the <a href="http://foss.in/2009/schedules/">main talks</a>, which are very good themselves, are not the main part of the event, it has come a long way.</p>

<p><img src="http://farm3.static.flickr.com/2665/4165131655_49ed8afcec_m_d.jpg" alt="Main Talks" /></p>

<p><a href="http://foss.in/fossin2009/understanding-foss-in-the-workouts.html">Workouts</a> were the main focus of the event. Unlike main talks where a speaker addresses a large audience, at workouts, group of interested people hack on something of interest. Workouts were introduced in foss.in last year and workouts <em>were</em> foss.in this year. New curious developers attend workouts, ask questions, go home, poke into the code and start submitting patches. And then they become new contributors to the project. No kidding. Here is an account of <a href="http://pradeepto.livejournal.com/18166.html">one such case</a> by Praddepto, an active KDE developer, who himself got into KDE at an earlier foss.in, similarly.</p>

<p><img src="http://farm3.static.flickr.com/2551/4164906099_71d5f8d8eb_m_d.jpg" alt="Workouts" /></p>

<p>There were workouts focussed on <a href="http://foss.in/2009/schedules/talkdetailspub.php?talkid=FEDORA">fedora</a>, <a href="http://foss.in/2009/schedules/talkdetailspub.php?talkid=KDE">kde</a>, <a href="http://foss.in/2009/schedules/talkdetailspub.php?talkid=36">debian</a>, <a href="http://foss.in/2009/schedules/talkdetailspub.php?talkid=MAEMO">maemo</a>, <a href="http://foss.in/2009/schedules/talkdetailspub.php?talkid=8">mozilla-weave</a>, <a href="http://foss.in/2009/schedules/talkdetailspub.php?talkid=40">wikipedia</a> and even <a href="http://foss.in/2009/schedules/talkdetailspub.php?talkid=34">the kernel</a>. The main talks ranged from <a href="http://foss.in/2009/schedules/talkdetailspub.php?talkid=44">Python Metaclasses and their use in Django</a>, that <a href="http://uswaretech.com/blog/2009/12/python-metaclasses-and-how-django-uses-them/">I presented</a>, to <a href="http://foss.in/2009/schedules/talkdetailspub.php?talkid=60">hardware breakpoints usage in Linux</a> and development of mobile applications using <a href="http://foss.in/2009/schedules/talkdetailspub.php?talkid=5">Maemo</a>. Several speakers had developed or mentored Google Summer of Code projects in their area.</p>

<p><img src="http://farm3.static.flickr.com/2804/4165892330_43dfb73d7b_m_d.jpg" alt="workouts" /></p>

<p>I was interested obviously, in the web development part of the conference. There was a workshop on <a href="http://foss.in/2009/schedules/talkdetailspub.php?talkid=41">web development using Pylons and a widget library</a>. The speaker Krishnakant has been using <a href="http://pylonshq.com/">Pylons</a> to develop <a href="http://gnukhata.gnulinux.in/">GNUKhata</a> a web based FOSS accounting software. <a href="http://www.sahanapy.org/">SahanaPy</a> is a disaster management system developed for help during Tsunami, using php. It is now being re-written using <a href="http://www.web2py.com/">Web2Py</a>. Automating python build process using <a href="http://www.web2py.com/">buildout</a> was also there. I am happy with Django, pip, fabric, git, vim, wing IDE and our tool chain in general; but it is good to know what other options are out there. I now, only appreciate our tool set more. <img src='http://uswaretech.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  On a more serious note, it is a challenging task ahead to try and fit in some of the takeaways from other tools and patterns of development into our existing ones.</p>

<p>There were talks on Cloud computing. <a href="http://foss.in/2009/schedules/talkdetailspub.php?talkid=11">Open source and clouds</a> by Archana Kumar and a <a href="http://foss.in/2009/schedules/talkdetailspub.php?talkid=29">talk by Janakiramm</a> on, its advantages, how infrastructure as a service (Ec2, Rackspace, Mozy) and platform as a service (GAE, Azure) compare. <a href="http://code.google.com/p/wiki-analysis/">WikiAnalysis</a> by <a href="http://en.wikipedia.org/wiki/User:Jackerhack">Kiran J</a>, shows in what sense a wikipedia page has evolved over the period, that aims to help admins to check Vandalism by <a href="http://en.wikipedia.org/wiki/Wikipedia:GAME">gaming the system</a>. A group of people with a common bias, can gradually lead the page to a different (biased) tone. Such cases may go unnoticed because it is not <a href="http://en.wikipedia.org/wiki/Wikipedia:SOCK">Sock Puppetry</a>, merely because many people are involved. Using the revision analysis, this tool, helps identify such cases.</p>

<p>Among the non-web talks and sessions, there was a detailed analysis into the <a href="http://foss.in/2009/schedules/talkdetailspub.php?talkid=46">Linux file system</a> by Lennart Poettering. Ramkumar from <a href="http://en.wikipedia.org/wiki/Indian_Institute_of_Technology_Kharagpur">IIT Kharagpur</a>(ranked as the top Indian Engineering institute) explained <a href="http://foss.in/2009/schedules/talkdetailspub.php?talkid=68">compiler optimization techniques</a> employed by <a href="http://code.google.com/p/unladen-swallow/">Unladen Swallow</a>. Gopal, a lead developer for php opcode cache APC, <a href="http://foss.in/2009/schedules/talkdetailspub.php?talkid=23">spoke about</a> <a href="http://freshmeat.net/projects/libjit/">Libjit</a>, and explained what it takes to build a fully functional jit, that is today in the heart of all interpreters. There were of course so <a href="http://foss.in/2009/schedules/">many more sessions</a>, that being held in parallel, I had to choose. The sessions on <a href="http://foss.in/2009/schedules/talkdetailspub.php?talkid=86">iphone bluetooth module</a>, <a href="http://foss.in/2009/schedules/talkdetailspub.php?talkid=80">palm pre</a> and <a href="http://foss.in/2009/schedules/talkdetailspub.php?talkid=48">scientific computing in python</a>, I&#8217;d have loved to attend. As for the <a href="http://lwn.net/Articles/248891/">Kernel</a>, Balbir Singh spoke on <a href="http://foss.in/2009/schedules/talkdetailspub.php?talkid=15">incremental development</a> and <a href="http://en.wikipedia.org/wiki/User:Peter_Ellis/Suparna_Bhattacharya">Suparna Bhattacharya</a> was present to assist for the workouts.</p>

<p>The keynotes were delivered on all the days by experts and were very good. The keynote by <a href="http://bluesmoon.livejournal.com/">Philip Tellis</a> called &#8220;<a href="http://foss.in/2009/schedules/talkdetailspub.php?talkid=55">Shut up and Hack</a>&#8221; started by saying &#8220;Have an itch, will scratch&#8221; and demonstrated a lot of quick hacks. It reminded me of the <a href="http://gist.github.com/6443">key note by Chris Wanstrath</a> on the need to have a side project. He spoke about the hacker mind set, how somebody is a hacker, that reminded me of Paul Buchchiet&#8217;s <a href="http://paulbuchheit.blogspot.com/2009/10/applied-philosophy-aka-hacking.html">the Hack definition</a>. <a href="http://www-clmc.usc.edu/Main/MrinalKalakrishnan">Mrinal KalaKrishnan</a>, flew in <a href="http://foss.in/2009/schedules/talkdetailspub.php?talkid=52">for the last key note</a>, from Los Angeles, where he is pursuing PHD in robotics. He, after working for 2 years on enterprise software, found his calling in robotics and is a lead developer of <a href="http://en.wikipedia.org/wiki/ROS_(Robot_Operating_System)">ROS</a> (Robot Operating System, a BSD licensed &#8220;meta operating system&#8221;).</p>

<p>There was music party organised on last 2 days, post the keynote. There was an indigenous rock band on friday by <a href="http://www.facebook.com/pages/Blues-Before-Sunrise/156177164004">Blues Before Sunrise</a> and <a href="http://raghudixit.com/">Raghu Dixit</a> performance on Saturday. Raghu Dixit sang the poems of a <a href="http://en.wikipedia.org/wiki/Shishunala_Sharif">9th century Kannada poet</a> but to the hip-hop and <a href="http://en.wikipedia.org/wiki/Enter_Sandman">rock music</a>. It was brilliant.</p>

<p><img src="http://farm3.static.flickr.com/2794/4165146115_6e45bef160_m_d.jpg" alt="Raghu Dixit" /></p>

<p>The event was organised by the <a href="http://foss.in/about/team">team foss.in</a> lead by <a href="http://en.wikipedia.org/wiki/Atul_Chitnis">Atul Chitnis</a>. Atul mentioned this was the last event he will be driving; however he will be advising the future ones. He also mentioned that, as free and open source software have become dominant anyway, from next year, the event can be about technology itself, and not restrict about free and open source alone.</p>

<p>All in all, <a href="http://blog.namei.org/2009/12/09/foss-in2009-great-conference-or-greatest-conference/">speakers</a>, delegates, organizers everyone agreed that this was the best foss.in ever.</p>

<p>The images used in the post above are licensed as CCA by <a href="http://www.flickr.com/photos/kbhargava/4153869960/">kishorebhargava</a>, <a href="http://www.flickr.com/photos/sujith-h/4160152863/">Sujith Haridasan</a>, <a href="http://www.flickr.com/photos/swatisani/4165131655/">swati_sani</a>, <a href="http://www.flickr.com/photos/x_jamesmorris/4164906099/">x_jamesmorris</a>, <a href="http://www.flickr.com/photos/swatisani/4165892330/">swati_sani</a>, <a href="http://www.flickr.com/photos/swatisani/4165146115/">swati_sani</a> respectively. <a href="http://gist.github.com/254066">Here is how</a> I found it!</p>


<p>Related posts:<ol><li><a href='http://uswaretech.com/blog/2009/10/pycon-india-2009/' rel='bookmark' title='Permanent Link: Pycon India 2009 : A Review'>Pycon India 2009 : A Review</a></li>
<li><a href='http://uswaretech.com/blog/2008/08/what-is-usware-technologies/' rel='bookmark' title='Permanent Link: What is Usware Technologies?'>What is Usware Technologies?</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://uswaretech.com/blog/2009/12/foss-in-2009-the-best-foss-in-ever/feed/</wfw:commentRss>
		<slash:comments>6</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 and Subscribe to our blog


Related posts:The magic [...]


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 [...]


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>
	</channel>
</rss>
