Getting Started with Django - My Experiences

Submitted By: Josh Juneau

Introduction

You may ask why we need another web framework, or what a different web framework may do to make my applications or development life cycle better. Obviously the developers of the Django web framework had some key goals in mind when they set upon their journey to create Django. I believe that their goal was simplicity and ability. These are two of the key factors that come into play for many of today's web frameworks. Ruby on Rails was the one of the pioneers in this area. Not long after, many other great application development languages came up with similar powerful frameworks. For example, Grails is also gaining momentum in the Groovy/Java developer community.

Now we come to Python, one of the most sexy, powerful, and easy to learn object oriented languages of our time. Of course we have some great web frameworks for Python. Pylons and Django are just a couple. Now let's port those into the Jython arena and sprinkle a bit of Java into the Python mix to create some very attractive web frameworks. Django does not disappoint, and I'd like to argue that it is one of the leading frameworks in the simplicity and ability arena. Let's dig into some basics with Django and find out what makes this framework so appealing.

This article is meant for the Django beginner. More importantly, we will cover basics for getting started with Django development with Jython. Rather than develop a separate set of examples for getting started, we will follow the Django documentation and I'll add extra information as needed. I hope to pick up with more advanced topics in future articles, so please stay tuned to the Jython Monthly distribution for more details.

Getting Ready to Tango with Django

First things first, we have to set up our environment. For those of you who would like to follow along, please be sure to download the following before continuing:

- The latest Jython distribution (2.5 alpha 3 at the time of this writing) http://www.jython.org - Django (1.0 at the time of this writing) http://www.djangoproject.com/ - django-jython libraries http://code.google.com/p/django-jython/

You will want to install all of these and ensure that the they reside in your classpath. Please visit the Django on Jython documentation for more details on setting up your environment.

Since we are using Jython, we can run our Django application on any Java servlet container. We can also mix any Java library into our application as needed...this is one of the most powerful reasons to use Django on Jython.

Database

Many of the major databases are supported at this time. However, there are a few that will not yet function with the Django framework on Jython. For instance, you will have to use an alternative to the DB2 database at this time. For more information, please take a look at the django-jython site. For the purposes of this article, I am advocating the Postgresql database to start out with Django.

In order to make Postgresql work with Django in the Python world, you must install the psycopg package (bindings). However, we have a bonus as Jython developers as this package is not required to run Django with Postgresql on Jython. Instead, for the database engine we simply specify "doj.backends.zxjdbc.postgresql" within the settings.py module.

Creating the Project and Models

Create Project

The first step in creating a Django application is to choose a location in which to store your code. Create a directory somewhere on your hard disk, and then open a command prompt or terminal. Change directories until you are positioned within your newly created directory. You also need to ensure that the jython and Django executables are in your CLASSPATH. Once you've ensured this information you are ready to begin creating your project.

jython django-admin.py startproject mysite

When you "cd" into the newly created "mysite" directory, you will see the following three important Jython files:

manage.py - Command-line utility for managing Django project settings.py - Configurations for the Django project urls.py - URL settings for the Django project

You now have created a fully functional project. You can start the test server now to ensure that everything is functional by issuing the following command:

jython manage.py runserver

You will see the following output:

Validating models... 0 errors found Django version 1.0-final-SVN-unknown, using settings 'mysite3.settings' Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C.

You can optionally specify a different port by appending the port number that you wish to use after the runserver command.

Database Setup

If you haven't already done so, create your Postgresql database for the test application at this time. Simply name the database test and create a user that we will use for our application to access the database. In order to setup the database for the project, you must edit the settings.py module. Remember, I am going to use the Postgresql database for the purposes of this article, but feel free to choose another if it is supported. You will need to change the following settings for the database:

DATABASE_ENGINE = 'doj.backends.zxjdbc.postgresql' # Our Jython Django Postgresql bindings DATABASE_NAME = 'test' # Or path to database file if using sqlite3. DATABASE_USER = 'username' # Not used with sqlite3. DATABASE_PASSWORD = 'passwd' # 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.

As the Django tutorial points out, it is a good idea to take a note of some other sections of the settings.py file at this time. Look at the following INSTALLED_APPS which are automatically included in your project for convienence:

django.contrib.auth -- An authentication system.

django.contrib.contenttypes -- A framework for content types.

django.contrib.sessions -- A session framework.

django.contrib.sites -- A framework for managing multiple sites with one Django installation.

In order to create the tables for your database, run the following command:

jython manage.py syncdb

Once you issue the command above, you should see the following output which will prompt you to enter information for creating a superuser account. It is important to do so at this time or you will need to take extra measures in order to create one later. Simply follow the directions as they are displayed in the terminal or command line.

Creating table auth_permission Creating table auth_group Creating table auth_user Creating table auth_message Creating table django_content_type Creating table django_session Creating table django_site You just installed Django's auth system, which means you don't have any superusers defined. Would you like to create one now? (yes/no):

Create Models

At this point, the Django project is set up and we are ready to create an application within it. In the Django environment, a project can contain one or more applications. For the purposes of this article, we will create the same application as the Django tutorial so that it is easier to follow along if you choose to do so. In this case, we are interested in creating an application which manages poll questions and answers.

The first step is to create the application itself. As stated above, we have create the project thus far but no application as yet. To do so, ensure that you are within the project mysite directory and issue the following command:

jython manage.py startapp polls

As you can see, the manage.py script plays an important role in constructing our Django projects/applications. At this point you should list the contents of the newly created polls directory and see that two jython modules have been created: models.py and views.py. These two modules are going to play an important role in the development and construction of our application model and view (obviously). As we continue to follow the Django tutorial, the next step is to open up the models.py file and edit the contents so that they look like this:

from django.db import models class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(max_length=200) votes = models.IntegerField()

This simply creates two classes which represent the Poll object itself and the Choice object for each poll. To learn more about the details of the syntax used for these classes, please take a look at the Django tutorial. For now, it is important to know that with this little bit of code, our application now has the information required to create database tables and views for controlling our Poll. In order to have the application included in our Django project (mysite), we need to adjust the the settings.py module a bit by adding the application to the list of INSTALLED_APPS. Open settings.py and go to the bottom of the file, adjust as follows:

INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'mysite.polls' )

Django now knows about our application and it can create the SQL required for our database objects as well as perform the work of creating the objects itself. In order to see the SQL that is required to create the objects for our database, issue the following command from within the mysite directory:

jython manage.py sql polls <<output>> BEGIN; CREATE TABLE "polls_poll" ( "id" serial NOT NULL PRIMARY KEY, "question" varchar(200) NOT NULL, "pub_date" timestamp with time zone NOT NULL ) ; CREATE TABLE "polls_choice" ( "id" serial NOT NULL PRIMARY KEY, "poll_id" integer NOT NULL REFERENCES "polls_poll" ("id") DEFERRABLE INITIALLY DEFERRED, "choice" varchar(200) NOT NULL, "votes" integer NOT NULL ) ; COMMIT;

In order to actually have Django create the objects, we use the following command from within the mysite directory:

jython manage.py syncdb << output >> Creating table polls_poll Creating table polls_choice Installing index for polls.Choice model

You can now look at the database and see the objects that have been created.

Working with the Framework

At this point you can begin to work with the framework at the shell level if you choose to do so. You can use the following command to get into the shell and then follow some of the ,http://docs.djangoproject.com/en/dev/intro/tutorial02/#intro-tutorial01 Django documentation] at the bottom of tutorial 1 to work with the model. Working with the model through the shell will help you to understand how the Django framework functions.

Delving into the Administrative Controls

In order to actually see your site up and running, you will need to activate the administrative controls. In my belief, this is one of the most powerful features of the Django framework. Years ago I began creating websites for clients that had all content stored in a database. I then created an administrative interface for the clients to use so that they could update the website content (the database content) at any time via a nice WYSIWYG editor. It is a great framework and the clients really enjoy using it to administer their sites. The Django framework gives you an administrative interface for free with each application you create. All site content is stored in the database, so it can all be updated via the use of the administrative console. Cascading style sheets can also be added and modified to change the look and feel of the site.

If you follow the Django Framework Tutorial 2, it will guide you into the right direction for creating and adjusting the administrative site. In this article, I will show you how to get started.

As the tutorial explains, the administrative site is not enabled by default. You must perform a few simple measures in order to activate the site. Follow the next few procedures to set up the administrative console for your Django website.

1) Add 'django.contrib.admin' to the settings.py INSTALLED_APPS setting. It should now resemble the following:

INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'mysite.polls', 'django.contrib.admin' )

2) Create a file named admin.py within your polls directory. Add the following to admin.py in order to register the Poll object to the administrative site:

from mysite.polls.models import Poll from django.contrib import admin admin.site.register(Poll)

3) Synchronize your data by running:

jython manage.py syncdb

4) Edit the urls.py file to resemble the following in order to allow access to the appropriate modules within your site:

from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^mysite/', include('mysite.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: (r'^admin/(.*)', admin.site.root), )

You can now start your application and log into it using the superuser account that you had created at the beginning of this article.

jython manage.py runserver

Please follow the Django Framework Tutorial 2 for more information on using the administrative site.

Use the following URL to log into your administrative site:

http://127.0.0.1:8000/admin

Conclusion

The Django framework slogan is 'The web framework for perfectionists with deadlines'. I must agree that Django helps to speed the process of generating web based applications. Although we did not get into an of the meat an potatoes in this article, hopefully the quick demo that was covered is enough to entice you into learning more about the framework. I am a Django newbie myself, and I find the development lifecycle of a Django web application to be very appealing. This would be especially true if there were IDE support for Django on Jython (it will be here soon). Until then, we can muddle through working with Django from terminal or command prompt...it is still easier than setting up a simple EJB application...although both EJB and Django have their own places in the world.

I hope to cover more details about the Django framework in future articles.

References

Leo Soto - Thanks for your assistance!

Django Project