Friday, March 8, 2013

Django

    Django  is used to build powerful, dynamic, interesting sites in extremely short time. Django is a valuable member of a new generation web frame work. web frame work provides a programming infrastructure for your applications.Direct way to build a python web app from scratch is to use Common Gateway Interface(CGI).Save the script with .cgi extension .In Django the CGI file is split it over four files(models.py, views.py, urls.py) and an HTML template.The model.py file contains a description of the database table, represented by a Python class.This class is called model. The view.py file contain the logic for the page. The url.py file specifies which view is called for given URL pattern. The HTML template that describes the design of the page.

Installation:

If you are using Linux distribution that includes a package Django. For installing Django in your system use the command:
 sudo apt-get install python-django 
Testing the Django installation: start python interactive interpreter by typing python. If the installation was successful, you should be able to import the module django by typing import django.

Hello World Project  

    Our first goal ,let's create a Web Page that outputs message "Hello World". You can take the first step in developing a Django application by creating a project. A project is collection of settings, including database configuration, Django-specific settings and application-specific settings.
In first step, For creating a project run the command:
django-admin startproject hello
This will create a 'hello' directory in your current directory
hello/
    __init__.py
    manage.py
    settings.py
    urls.py
These files are as follows:
__init__.py: A file required for python to treat the hello directory as a package.
manage.py:  A command-line utility that lets you interact with this Django project in various ways.      
                   Type python manage.py help to get a feel for what it can do.
settings.py: Settings/configuration for this Django project.
urls.py: The URLs for this Django project.

Views

     To display a simple message "Hello World" in browser, change into your project directory hello and create  an empty file views.py. Then add the content into it:
from django.http import HttpResponse

def hello(request):
      return HttpResponse("Hello World!")
Let's step through this code: First we import HttpResponse, which live in django.http module. Next we define the view function called hello. Each view function takes at least one parameter called request. This is an object that contains information about the current Web request that has triggered this view.

URLconf

     To hook a view function to a particular URL we need to tell Django explicitly that we’re activating this view at a particular URL.
 Edit urls.py file as follows:
from django.conf.urls.defaults import *

from hello.views import hello

urlpatterns = patterns('',
           ('^hello/$', hello),
)
The first line imports all objects from the django.conf.urls.defaults module. This includes a function called patterns.Then we imported the hello view from its module – hello/views.py, which translates into hello.views in Python import syntax.Next, calls the function patterns and saves the result into a variable called urlpatterns. We added the line ('^hello/$', hello), to urlpatterns. This line is referred to as a URLpattern. It’s a Python tuple in which the first element is a pattern-matching string and the second element is the view function to use for that pattern.
Now test the code in your local machine using the command:
python manage.py runserver
You will see something like this:
Validating models...

0 errors found.

Django version 1.0, using settings 'hello.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Now that it’s running, visit http://127.0.0.1:8000/hello/ with your Web browser. You’ll see a “Hello World!” page .

Creating a Students details application


     You can create a students application by using  Some important modules are render_to_response and HttpResponse.  You can create this students application by editing view.py and urls.py using my source code in github. The link is Here.

Django model:

     In this example we use sqlite3 for handling  data. Django provides a range of options for storing data.  sqlite3 library used to connect SQLite database, retrieve some records, and feed them to a template for display as Web page.
First, we needed to take care of some initial configuration. we need to tell django which database server to use how to connect to it.
Edit settings.py as:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': '/home/recursivelab/djcode/students/student.db',                      # Or path to database file if using sqlite3.
        'USER': '',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}  

DATABASE_NAME tells Django the name of your database.If you’re using SQLite, specify the full filesystem path to the database file on your filesystem  Does not change other things in this file. Once you've entered those settings and saved settings.py.
In shell, type these commands to test your database configuration:

>>> from django.db import connection
>>> cursor = connection.cursor()
If nothing happens, then your database is configured properly

Your students-App:

     Now it’s time to create a Django app – a bundle of Django code, including models and views, that lives together in a single Python package and represents a full Django application. Within the students project directory, type this command to create a student app:

python manage.py startapp student
It does create a books directory within the student directory. Let’s look at the contents of that directory:
student/
    __init__.py
    models.py
    tests.py
    views.py

Your model:

     The first step in using this database layout with Django is to express it as Python code. In the models.py file that was created by the startapp command, enter the following:
from django.db import models

class Students(models.Model):
    name = models.CharField(max_length=30)
    sex = models.CharField(max_length=15)
    age = models.CharField(max_length=10)
    mark = models.CharField(max_length=15)
It define the model of database. The first thing to notice is that each model is represented by a Python class that is a subclass of django.db.models.Model. We've written the code; now let’s create the tables in our database. In order to do that, the first step is to activate these models in our Django project. We do that by editing the settings.py file.It is looks like this:
MIDDLEWARE_CLASSES = (
    # 'django.middleware.common.CommonMiddleware',
    # 'django.contrib.sessions.middleware.SessionMiddleware',
    # 'django.contrib.auth.middleware.AuthenticationMiddleware',
)

INSTALLED_APPS = (
    # 'django.contrib.auth',
    # 'django.contrib.contenttypes',
    # 'django.contrib.sessions',
    # 'django.contrib.sites',
    'students.student',
)
Temporarily comment out all four of those strings by putting a hash character (#) in front of them. Comment out the default MIDDLEWARE_CLASSES setting, too.Then, add 'students.student' to the INSTALLED_APPS list.
Now that the Django app has been activated in the settings file, we can create the database tables in our database. First, let’s validate the models by running this command:

python manage.py validate
 If all is well, you’ll see the message 0 errors found.If your models are valid, run the following command for Django to generate CREATE TABLE statements for your models in the student app
python manage.py syncdb
Now the table is created.Finally run the command:

python manage.py runserver

The server is running at the address http://127.0.0.1:8000/, so open up a Web browser and go to http://127.0.0.1:8000/.

The full source code is available Here

No comments:

Post a Comment