Advertisement

Agile Framework - Django

HTML clipboard

In a number of articles in DeveloperIQ we have earlier seen how Rails, being the first open source web2.0 framework and with its new strategies, has changed the way web development is done. We have also seen how the Java world tries to adopt it, without giving up the Java platform, in JRuby on Rails, Grails etc. and Why? Development with Rails is easy, but the same cannot be said about its deployment; nor can we call it efficient as the server creates a process per request. So deployment on time-tested Java platform and servers which support multi-threading is their main motive. The results of similar attempts by the Pythonists are in the form of TurboGears, Pylon etc. Django, though Rails-like, was not influenced by Rails. Adrian Holovaty, its Project lead says “ People tend to not do very much research and to assume that Django is a response to it(Rails), that it’s a sort of a “me too” framework. But actually, almost four years ago was when we started to piece it together. Rails was open-sourced first, while Django was still a proprietary project.” Django started as an internal project at the Lawrence Journal-World newspaper in 2003. The web development team there often had to implement new features or even entire applications within hours. Therefore, Django was created to meet the fast deadlines of journalism websites, at the same time keeping the development process clean and maintainable. By the summer of 2005, Django became mature enough to handle several high traffic sites, and the developers decided to release it to the public as an Open Source project. The project was named after the jazz guitarist Django Reinhardt. At production stage, with mod_python, Django can be easily deployed on Apache. In popularity Django is only behind Rails in agile frameworks, as can be seen from the number of books published on it. Django is, like Rails, a complete web development environment. It has a web server for development, ORM and scripts to carry out tasks that cover all aspects of web development. Django book says “ it provides high-level abstractions of common Web development patterns, shortcuts for frequent programming tasks, and clear conventions for how to solve problems.” . 

Smt Geetha Ganesan in a series of articles in DeveloperIQ from May 2009 has shown its use on Linux platform . But, like any ordinary user, we are interested in the framework for Windows platform and in the IDEs. Though support for Python is available from NetBeans6.5, support for Django is expected from version 7 only. A third party plug-in is said to be available but we have to build it from source. Eclipse users, they say, can use PyDev. For the time being we will be using only the command prompt and IDLE, the Python editor. Like, instant Rails, Instant Django is available. You can download it from the web site instantdjango.com. The exe file is about 22mb and you can extract it to a folder and find that it contains two folders python26 and utilities and a start.bat file. If you click the bat file the command prompt is ready to accept your commands .There is no installation and we have got a standalone Django development environment. A separate Python installation may pose problems when we use instant Django. So we will try to have our own windows installation of Django. What are the requirements:

1) Python . You know Django is a web framework written in Python. DeveloperIQ cds have carried from time to time various Python versions. For Django, you can install any version above 2.3 (not Python3.0 for which compatible Django is yet to come).Version 2.5 and above contain the database SQlite.

2) Django –is available only as tar.gz file and you can download and unpack it using WinRar or WinZip.

3) system variable path has to edited to add path to your python site-packages and Scripts folders which contain python scripts. For example if your Python2.5 is in your C:\ add to the path the following:

a) C:\Python25\Lib\site-packages b)C:\Python25\Scripts

After un-packing Django to any directory, cd to the folder in command prompt and run the command setup.py install 
This command will install Django in your Python installation's site-packages directory as an egg file. Now going to the Python interactive shell and type >>>

import django 

If the installation is ok, there will be no message. Otherwise will be an error message. 

Create a folder for creation of Django projects in your system – no restriction that it should be created in document root. Using cd command change to the directory in command prompt. 

Django provides two commands — django-admin.py and manage.py — that you can use to perform administrative tasks such as creating a project skeleton and creating a project database. But django-admin.py is project-independent, whereas manage.py is generated when you create a new project and should be used only when working with that project.

Execute the command 

   
                 django-admin.py startproject demo1

The directory demo1 and the following files are created.

........................................................................
demo1/
__init__.py
manage.py
settings.py
urls.py


These files are as follows:

change to demo1 directory using cd command and execute the command 

mange.py runserver

Tthe difference of manage.py with django-admin.py lies only in the fact that it has to be executed from within a project.
You will get the message “validating models----development server is running at http://127.0.0.1:8000”
You can see that things are working and quit the server using Ctrl+c. 
Start your MySQL server. Connect to it through HeidiSQL. Create the database phone, if you have not done the same on earlier occasions. No table need be created for the purpose of this application. From the model class we specify, the framework will do the same.
Now we can start creating necessary files within the project.
Execute the command

manage.py startapp books

The startapp command produces no output, but creates a subdirectory named books containing the three files described in the following table.

File Description
__init__.py As with the project, this is an empty file that identifies this directory as a 
Python package.

models.py This is the file in which you’ll code your model classes.
views.py This is the file in which you’ll code your views.

We can also start customizing the framework-generated files with IDLE . First Go to C:\django-projects\demo1directory in My Computer and right click on settings.py and choose Edit with IDLE, the file will be open in the editor. Fill up the following information
DATABASE_ENGINE = 'mysql' 
DATABASE_NAME = 'phone' 
DATABASE_USER = 'sekaran' 
DATABASE_PASSWORD = 'sekaran'

Towards the end in INSTALLED_APPS Add ‘demo1.books’
After addition it should appear as:
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
‘demo1.players’
)

Open the folder demo1\books and right click on the file models.py and choose Edit with IDLE .Complete the file as follows;

from django.db import models
class Book(models.Model): 
title = models.CharField(max_length=100) 
pub_date = models.DateField()

Go to command prompt and execute the command 

manage.py sql books

The framework will create necessary sql to create books.book table with necessary columns for the class Book in model.py.
Now we have to actually create the table using the same. For the purpose, execute the command

manage.py syncdb

Necessary tables will be created and you will be also asked to create a super-user. Answer the queries and a super user will be created.
Now execute the command 

manage.py shell

The command prompt will become python interactive shell.
In the shell, Enter following commands one after another 

1)from demo1.books.models import Book 
2)b1=Book(title=”Python made Easy”,pub_date=’2007-12-12’)
3)b1.save()
4)b2=Book(title=”Jython made Easy”,pub_date=’2008-10-12’)
5)b2.save() 
6)b1.title
7)b2.title

The above commands and their results in the shell are in Figure 2:



You may ask what about going to the browser and adding records. Some more tweaking to the application is necessary. First get out of the interactive shell by typing exit().

1)In settings.py add ‘django.contrib.admin’ to INSTALLED_APPS
2)Execute manage.py syncdb to update the above change to INSTALLED_APP
3)Edit urls.py by un-commenting certain lines there..The code of new urls py is given below


urls.py 
from django.conf.urls.defaults import *
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',

(r'^admin/', include(admin.site.urls)),



r’^admin/’ is a regular expression and we will see about it and url patterns in our article on views in Django. “r” denotes that Django should evaluate the regular expression as a raw string ie without evaluating escape character like “/”. The biggest problem of Python is indentation. Spaces at the beginning of a line can cause havoc. It is better you use IDLE’s Run->Run Module. If there is any indentation error you can rectify. Ignore other errors pointed out due to certain other reasons. 

The above steps are meant to manage users -restrict your site to only admin users. To enable them to add/edit records in our model one more step is necessary. Create a file admin.py in your demo1/books folder with IDLE by clicking File->New Window. The code for it is given below:

admin.py 
from django.contrib import admin
from demo1.books.models import Book
admin.site.register(Book)


Now you can execute the command 
manage.py runserver
Go the browser and type http://localhost:8000/admin and see Figure-3 in the browser. Without entering correct username and/or password, if you login you will get Figure-4 If you give correct username and password you will get Figure 5.From Figure 5 you can see this user is a super user who can add/change Groups, Users, records in model. When we click the link Books Add we get Figure 6 and the same can be used to add records. You can see that the claim that Django is a high-level web framework that simplifies website development is true . As a high-level web framework, like Rails, Django abstracts much of the web development process, allowing developers to quickly implement database-backed websites using dynamic web pages. The added advantage it is written in Python-a language used by many others.
Hitherto we saw how to install Django in Windows and how to create a project and start an application and create a model class and add records to model through interactive python shell or administrative interface. The other layers of Django are View and Template We will see about them in future.














Added on July 31, 2010 Comment

Comments

#1

Vamshi Krishna commented, on August 6, 2010 at 8:43 p.m.:

I find little difficult working With Django. Can you provide me good tutorial.

Post a comment