Django Introduction Osscamp Delhi September 08 09 2007 Mir Nazim

download Django Introduction Osscamp Delhi September 08 09 2007 Mir Nazim

If you can't read please download the document

Transcript of Django Introduction Osscamp Delhi September 08 09 2007 Mir Nazim

DJANGO

WEB APPLICATION FRAMEWORK

FOR

PERFICTIONISTS WITH DEADLINES

Presented byMir [email protected]

Django at Glance

A high-level Web framework.

Eases the pain of building dynamic Web sites.

Abstracts common problems of Web development

Provides shortcuts for frequent programming tasks.

Django

provides a method of mapping requested URLs to code that handles requests

makes it easy to display, validate and redisplay HTML forms

converts user-submitted input into data structures that can be manipulated conveniently

helps separate content from presentation via a template system

...And Django

conveniently integrates with storage layers

lets you work more productively, at a higher level of abstraction

simply gets out of your way

Django is a

MVT architecture

Models

Describes you data structure/schema

Views

Controls what a user seesController in MVC snese

Templates

How user sees it

Sample App

Polls Application

There are polls

There are choices

User votes on polls

Installation

Install Python

Install Apache and mod_python

Get your database

Django works with PostgreSQL, MySQL, Oracle and SQLite

We will use SQLite for our example

Install python bindings MySQLdb, psycopg, cx_Oracle or pysqlite

Downlowload Django and Install it.

see

http://www.djangoproject.com/documentation/install/

Start the project

$ django-admin.py startproject mysite

$ cd mysite

$ ls

__init__.py manage.py settings.py urls.py

What only four file? Hah! its joke

Start the app

$ python ./manage.py startapp polls

polls/

__init__.py

models.py

views.py

Apps are stand-alone packages that are plugable from one django install to other

Apps are plugable as long as you make them so

Models

In mysite/polls/models.py

from django.db import models

class Poll(models.Model):

question = models.CharField(maxlength=200)

pub_date = models.DateTimeField('date published')

class Choice(models.Model):

poll = models.ForeignKey(Poll)

choice = models.CharField(maxlength=200)

votes = models.IntegerField()

A little config

In mysite/settings.py

INSTALLED_APPS = (

'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.sites',

'mysite.polls',

)

DB config

In mysite/settings.py

DATABASE_ENGINE = 'sqlite3'

DATABASE_NAME = 'mysite.sqlite'

DATABASE_USER = ''

DATABASE_PASSWORD = ''

DATABASE_HOST = ''

DATABASE_PORT = ''

Spit the SQL

$ python manage.py sql polls

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"),

"choice" varchar(200) NOT NULL,

"votes" integer NOT NULL

);

COMMIT;

Make my DB

$ python manage.py syncdb

Generates SQL from model and populates your database with the shema

Using ORM & DB API

$ python manage.py shell

This takes care of Putting mysite on sys.path

# Import the model classes we just wrote.

>>> from mysite.polls.models import Poll, Choice

# No polls are in the system yet.

>>> Poll.objects.all()

[]

# Create a new Poll.

>>> from datetime import datetime

>>> p = Poll(question="What's up?", pub_date=datetime.now())

# Save the object into the database. You have to call save() explicitly.

>>> p.save()

>>> p.id

1

# Access database columns via Python attributes.

>>> p.question

"What's up?"

>>> p.pub_date

datetime.datetime(2005, 7, 15, 12, 00, 53)

# Change values by changing the attributes, then calling save().

>>> p.pub_date = datetime(2005, 4, 1, 0, 0)

>>> p.save()

# objects.all() displays all the polls in the database.

>>> Poll.objects.all()

[]

Automatic Admin UI

A dynamic admin interface

Its not just scaffolding

its the whole house

Actually might be usefull for you

How to do it

In mysite/settings.py

add "django.contrib.admin" in INSTALLED_APPS list

In mysite/urls.py

uncomment the line below Uncomment this for admin:

(r'^admin/', include('django.contrib.admin.urls')),

$ python ./manage.py syncdb

Make Polls part of Admin

class Poll(models.Model):

# ...

class Admin:

pass

Views

Views are data that user sees

But not neccessarily how data looks

Design your URLs

All urls go into urls.py

Defined using regular expression

(regular expression, Python callback function [, optional dictionary])

In urls.py

from django.conf.urls.defaults import *

urlpatterns = patterns('',

(r'^polls/$', 'mysite.polls.views.index'),

(r'^polls/(?P\d+)/$', 'mysite.polls.views.detail'),

(r'^polls/(?P\d+)/results/$', 'mysite.polls.views.results'),

(r'^polls/(?P\d+)/vote/$', 'mysite.polls.views.vote'),

)

Write a view

from django.http import HttpResponse

# /polls

def index(request):

return HttpResponse("Hello, world. You're at the poll index.")

# /polls/

def detail(request, poll_id):

return HttpResponse("You're looking at poll %s." % poll_id)

Actually doing useful stuff

from django.template import Context, loader

from mysite.polls.models import Poll

from django.http import HttpResponse

def index(request):

latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]

t = loader.get_template('polls/index.html')

c = Context({

'latest_poll_list': latest_poll_list,

})

return HttpResponse(t.render(c))

Templates

$ mydir templates

and in settings.py add the path to templates TEMPLATES_DIR

TEMPLATE_DIRS = (

"/home/mir/mysite/templates",

)

templates/index.html

{% if latest_poll_list %}

  • {% for poll in latest_poll_list %}

  • {{ poll.question }}

    {% endfor %}

{% else %}

No polls are available.

{% endif %}

Decopuling the url config

In settings.oy replace all polls urls with

(r'^polls/', include('mysite.polls.urls')),

Create a polls/urls.py

urlpatterns = patterns('mysite.polls.views',

(r'^$', 'index'),

(r'^(?P\d+)/$', 'detail'),

(r'^(?P\d+)/results/$', 'results'),

(r'^(?P\d+)/vote/$', 'vote'),

)

There is more to it

newforms package

improves form handling than previous releases

generic views

no need to code obvious views

Sessions

Caching, Internatalization, Localization, Custom Middleware, Authentication, RSS frameworks, Multi Site deploymens,

Resources

www.djangoproject.com

www.djangosnippets.com

www.djangosite.org

Thank You

?

QUESTIONS

Muokkaa otsikon tekstimuotoa napsauttamalla

Muokkaa jsennyksen tekstimuotoa napsauttamalla

Toinen jsennystaso

Kolmas jsennystaso

Neljs jsennystaso

Viides jsennystaso

Kuudes jsennystaso

Seitsems jsennystaso

Kahdeksas jsennystaso

Yhdekss jsennystaso