Introduction to Django
时间:2009-04-06 来源:cobrawgl
Django is opensource Web framework written in Python. Django loosely follows MVC design pattern. Django being written in Python you should have some knowledge of Python. You can download Django from http://www.djangoproject.com/download. I have been using Django since its 0.96 release. Today I decided to write a small application using it.
As Django follows design pattern similar to MVC lets first understand what MVC is:
MVC Design Pattern
There are various MVC frameworks available like CakePHP, Zend Framework for PHP developers, Struts for Java developers, Catalyst for Perl developers and Rails for Ruby developers.
Model
Model is generally used to interact with the databases. Suppose you are working on some social networking site and you want to get user’s friends list. All the queries regarding this is written in Models. The resultant output is passed on to Controller.
Controller
All the business logic goes here. Consider the same scenario where user wants to get his own friends list. At this time Controller will get some inputs from user. Inputs may be number of friends he wants to see at a time or may be the number of users from India. Based on the user inputs the Controller with interact with Model to get the friends list. And then the list is passed to View.
View
View are used for creating User Interface. In our case User Interface will be based on the friends list recieved from Controller. View will take care of how the list is going to be displayed and what details are to be displayed.
MVC pattern allows us the write the code which is easier to maintain, Programmer writes Model and Controller and at the same time Designer can create View. And also few changes somewhere wont affect the entire system. We can say that MVC applications are loosely coupled.
Django follows slightly modified version of MVC design pattern called MTV design pattern. MTV stands for Model-Template-View. Now lets see how Django’s MTV pattern is:
MTV Design Pattern
Model
A Model in Django is a Python class which represents a table from database. You dont need to write complex SQL queries to get records from Database. You can do it by writing Python code itself.
View
In Django views contains all business logic code.
Template
These are the HTML pages which create User Interface. Django comes with very powerfull templating system.
Get Set Code..
Now its time to create our application. The application will be a simple address book. We will make use of Django’s Admin to add records and will create a view to display the contacts in address book.
Lets create a new Django project. Run the following command:
view plaincopy to clipboardprint?- $ django-admin.py startproject djangoapp
$ django-admin.py startproject djangoapp
A new directory called list will be created which contains following files:
__init__.py: So that Python treats this directory as package.
manage.py: Command line utility to interact with our project.
settings.py: Configuration file for our project.
urls.py: URL mappings of our project.
Django comes with light weight Web server. DONT USE IT FOR PRODUCTION. Next
view plaincopy to clipboardprint?- $ cd djangoapp
$ cd djangoapp
And boot the webserver:
view plaincopy to clipboardprint?- $ django-admin.py manage.py runserver
$ django-admin.py manage.py runserver
This will start Web server on port 8000(default). Visit http://localhost:8000/ from your browser. You should see “It worked!” message like this:
Now lets configure database connection for our application. Open the settings.py file. You will see the following lines:
view plaincopy to clipboardprint?- DATABASE_ENGINE = ''
- DATABASE_NAME = ''
- DATABASE_USER = ''
- DATABASE_PASSWORD = ''
DATABASE_ENGINE = '' DATABASE_NAME = '' DATABASE_USER = '' DATABASE_PASSWORD = ''
For our application we are using MySQL and the database name is “addressBook”. So we have to edit above lines as follows:
view plaincopy to clipboardprint?- DATABASE_ENGINE = 'mysql'
- DATABASE_NAME = 'addressbook'
- DATABASE_USER = 'root'
- DATABASE_PASSWORD = 'password'
DATABASE_ENGINE = 'mysql' DATABASE_NAME = 'addressbook' DATABASE_USER = 'root' DATABASE_PASSWORD = 'password'
Django’s models requires new application to be created. So type the following command to create new application:
view plaincopy to clipboardprint?- $ python manage.py startapp addressbook
$ python manage.py startapp addressbook
This will create new directory called friends with the following contents:
__init.py__
models.py
views.py
Change directory to friends:
view plaincopy to clipboardprint?- $ cd addressbook
$ cd addressbook
Edit models.py and write following contents in it:
view plaincopy to clipboardprint?- from django.db import models
- class Contacts(models.Model):
- name = models.CharField(max_length=30){ margin: 0.79in }
- phone = models.CharField(max_length=30)
- email = models.EmailField()
from django.db import models class Contacts(models.Model): name = models.CharField(max_length=30){ margin: 0.79in } phone = models.CharField(max_length=30) email = models.EmailField()
The class Contacts will be a table in database and the variables ‘name’, ‘phone’ and ‘email’ will be the columns of Contacts table. Yeah.. no need of writing SQL queries, Django can do it for you. We will see that later.
Now we need to tell Django to use this ‘Contacts’ model(djangoapp/addressbook/models.py). Edit settings.py file, and goto INSTALLED_APPS section and add ‘addressbook’. It should look as follows:
view plaincopy to clipboardprint?- INSTALLED_APPS = (
- 'django.contrib.auth',
- 'django.contrib.contenttypes',
- 'django.contrib.sessions',
- 'django.contrib.sites',
- 'addressbook',
- )
INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'addressbook', )
Validating Models
view plaincopy to clipboardprint?- $ python manage.py validate
$ python manage.py validate
The above command will validate models in your application. It will check for syntax and logical errors. If everything is ok then it should give 0 errors found message. And now run the following command to generate queries of the models:
view plaincopy to clipboardprint?- $ python manage.py sqlall addressbook
$ python manage.py sqlall addressbook
In above command addressbook is the name of our app for which queries are to be generated. This wont create table in the database, it will just output the queries which will be executed at the time of creating tables. The table name will start with ‘addressbook_’ and ‘id’ column(Primary Key) is added by default. And now syncdb to create tables:
view plaincopy to clipboardprint?- $ python manage.py syncdb
$ python manage.py syncdb
This will execute the statements which where generated by sqlall command. Now as we have our database ready, we will make use of Django’s Admin now. To use Admin we need to add ‘django.contrib.admin’ to INSTALLED_APPS:
view plaincopy to clipboardprint?- INSTALLED_APPS = (
- 'django.contrib.auth',
- 'django.contrib.contenttypes',
- 'django.contrib.sessions',
- 'django.contrib.sites',
- 'addressbook',
- 'django.contrib.admin',
- )
INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'addressbook', 'django.contrib.admin', )
And now again sync the database:
view plaincopy to clipboardprint?- $ python manage.py syncdb
$ python manage.py syncdb
As we have added admin in INSTALLED_APPS, syncdb will now ask you to create superuser for the application. We need superuser to access admin. Now we have to add our model to admin. To do that create a file called admin.py in our application(i.e. Under djangoapp/addressbook/):
view plaincopy to clipboardprint?- from django.contrib import admin
- from djangoapp.addressbook.models import Contacts
- admin.site.register(Contacts)
from django.contrib import admin from djangoapp.addressbook.models import Contacts admin.site.register(Contacts)
And finally edit urls.py. Add (r’^admin/(.*)’, admin.site.root) in urlpatters so that we can access admin at http://localhost:8000/admin. Our urls.py file looks like this:
view plaincopy to clipboardprint?- from django.conf.urls.defaults import *
- # Uncomment the next two lines to enable the admin:
- from django.contrib import admin
- admin.autodiscover()
- urlpatterns = patterns('',
- # Uncomment the next line to enable the admin:
- (r'^admin/(.*)', admin.site.root),
- )
from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Uncomment the next line to enable the admin: (r'^admin/(.*)', admin.site.root), )
Now run the server:
view plaincopy to clipboardprint?- $ python manage.py runserver
$ python manage.py runserver
You can access admin at http://localhost:8000/admin.
Click on Add link under Addressbook and start adding to the list. Django admin is very useful and it also provide every kinds of validations. Now we will write a view to display the added contacts. Open the file views.py under addressbook and write the following:
view plaincopy to clipboardprint?- from django.shortcuts import render_to_response
- from models import Contacts
- def contacts(request):
- contacts_list = Contacts.objects.all()
- return render_to_response('contacts_list.html', {'contacts_list': contacts_list})
from django.shortcuts import render_to_response from models import Contacts def contacts(request): contacts_list = Contacts.objects.all() return render_to_response('contacts_list.html', {'contacts_list': contacts_list})
In the above code we create a function called contacts. We retrieve all the records from Contacts model using Contacts.objects.all() . We use render_to_response to send variables to templates. The first argument is template name (contacts_list.html in our case) and second argument is a dictionary. The key in dictionary is the name of the variable that can be accessed in template contacts_list.html. The value in the dictionary is the variable that we will access in template. We have to create a directory called templates in addressbook and we will place contacts_list.html. In contacts_list.html we just loop through the contacts_list dictionary which we had passed in contacts function in views.py:
view plaincopy to clipboardprint?- <html>
- <head><title>Address Book</title><head>
- <h1>Address Book</h1>
- <body>
- <table>
- <tr>
- <td>Name</td>
- <td>Phone</td>
- <td>Email</td>
- </tr>
- {% for contact in contacts_list %}
- <tr>
- <td>
- {{ contact.name }}</td>
- <td>
- {{ contact.phone }}</td>
- <td>
- {{ contact.email }}</td>
- </tr>
- {% endfor %}</table>
- </body>
- </html>
<html> <head><title>Address Book</title><head> <h1>Address Book</h1> <body> <table> <tr> <td>Name</td> <td>Phone</td> <td>Email</td> </tr> {% for contact in contacts_list %} <tr> <td> {{ contact.name }}</td> <td> {{ contact.phone }}</td> <td> {{ contact.email }}</td> </tr> {% endfor %}</table> </body> </html>
To see the output we have to map url to addressbook view. Change the urls.py so that it looks as follows:
view plaincopy to clipboardprint?- from django.conf.urls.defaults import *
- from contacts.views import contacts
- # Uncomment the next two lines to enable the admin:
- from django.contrib import admin
- admin.autodiscover()
- urlpatterns = patterns('',
- (r'^show/', contacts),
- # Uncomment the next line to enable the admin:
- (r'^admin/(.*)', admin.site.root),
- )
from django.conf.urls.defaults import * from contacts.views import contacts # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^show/', contacts), # Uncomment the next line to enable the admin: (r'^admin/(.*)', admin.site.root), )
You can see the list of contacts at http://localhost:8000/show/.
In this post we covered some basics about Django like admin, creating a view and using templates. I will be posting more about Django soon.
References: http://www.djangobook.com