Web Development With Django
A Basic Introduction
Ganga L
Python Frameworks
Django
CherryPy
Pylons
Flask
Bottle
Tipfy
Pyramid
Cubic Web
GAE framework
Outline
What Is Django?
Project Structure
Data Handling
The Admin Interface
Django Forms
Views
Templates
What Is Django?
High-level framework for rapid web development
Complete stack of tools
Data modelled with Python classes
Production-ready data admin interface, generated dynamically
Elegant system for mapping URLs to Python code
Generic views’ to handle common requests
Clean, powerful template language
Components for user authentication, form handling, caching . . .
Creating Projects & Apps
Creating a project:
[Link] startproject mysite
Creating an app within a project directory:
cd mysite
./[Link] startapp poll
Project Structure
A Python package on your PYTHONPATH
Holds project-wide settings in [Link]
Holds a URL configuration (URLconf) in [Link]
Contains or references one or more apps
App
A Python package on your PYTHONPATH
(typically created as a subpackage of the project itself)
May contain data models in [Link]
May contain views in [Link]
May have its own URL configuration in [Link]
Up & Running
Set PYTHONPATH to include parent of your project directory
Define new environment variable DJANGO_SETTINGS_MODULE,
setting it to project settings ([Link])
3 Try running the development server:
/[Link] runserver
Creating The Database
Create database polls in youe database
Sync installed apps with database:
./[Link] syncdb
Create Project
Create Project mysite
mysite/
[Link]
mysite/
__init__.py
[Link]
[Link]
Create Application
python [Link] startapp polls
polls/
__init__.py
[Link]
[Link]
[Link]
Create Models
from [Link] import models
class Poll([Link]):
question = [Link](max_length=200)
pub_date = [Link]('date published')
class Choice([Link]):
poll = [Link](Poll)
choice_text = [Link](max_length=200)
votes = [Link](default=0)
The Data Model
A description of database layout, as a Python class
Normally represents one database table
Has fields that map onto columns of the table
Many built-in field types
CharField, TextField
IntegerField, FloatField, DecimalField
DateField, DateTimeField, TimeField
EmailField, URLField
ForeignKey . . .
Installed App
INSTALLED_APPS = (
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'polls',
)
python [Link] syncdb
Registering Models in Admin
In [Link] in the Poll app:
from [Link] import admin
from [Link] import Poll
[Link](Poll)
In [Link]:
from [Link] import patterns, include, url
from [Link] import admin
[Link]()
urlpatterns = patterns('',
url(r'^admin/', include([Link])),
)
Generic Views
Provide ready-made logic for many common tasks:
Issuing a redirect
Displaying a paginated list of objects
Displaying a ‘detail’ page for a single object
Yearly, monthly or daily listing of date-based
objects
‘Latest items’ page for date-based objects
Object creation, updating, deletion (with/without
authorisation)
Generic Views Example
[Link]
def index(request):
return HttpResponse("Hello, world. You're at the poll index.")
[Link]
from [Link] import *
from polls import views
urlpatterns = patterns('',
url(r'^$', [Link], name='index')
)
Main [Link]
from [Link] import patterns, include, url
from [Link] import admin
[Link]()
urlpatterns = patterns('',
url(r'^polls/', include('[Link]')),
url(r'^admin/', include([Link])),
)
Creating & Saving Objects
Invoke constructor and call save method:
call create method of Club model manager:
poll = Poll(question='what is your DOB? ', year='1986)
[Link]()
[Link](question='what is your DOB? ', year='1986)
View Function
Takes an HTTPRequest object as a parameter
Returns an HTTPResponse object to caller
Is associated with a particular URL via the URLconf
HTTP Response
from datetime import date
from [Link] import HttpResponse
def today(request):
html = '<html><body><h2>%s</h2></body></html>' % [Link]()
return HttpResponse(html)
from [Link] import render_to_response
From [Link] import Poll
def poll_details(request):
today = [Link]()
poll_data = [Link]()
return render_to_response('[Link]', locals(), context_instance =
RequestContext(request))
Templates
Text files containing
Variables, replaced by values when the template
is rendered[
{{ today }}
Filters that modify how values are displayed
{{ today|date:"D d M Y" }}
Tags that control the logic of the rendering
process
{% if name == "nick" %}
<p>Hello, Nick!</p>
{% else %}
<p>Who are you?</p>
{% endif %}
Template Example
[Link]
TEMPLATE_DIRS = (
[Link]([Link](__file__), 'templates'),
)
templates/club/club_list.html
{% extends "[Link]" %}
{% block title %}Clubs{% endblock %}
{% block content %}
<h1>Clubs</h1>
<ol>
{% for club in clubs %}
<li>{{ club }}</li>
{% endfor %}
</ol>
{% endblock %}
Django Forms
A collection of fields that knows how to validate itself and display
itself as HTML.
Display an HTML form with automatically generated form widgets.
Check submitted data against a set of validation rules.
Redisplay a form in the case of validation errors.
Convert submitted form data to the relevant Python data types.
Django Model Forms
from [Link] import ModelForm
import [Link] import Poll
class PollForm(ModelForm):
class Meta:
model = Pole
A Basic Django Forms
Standard [Link]
Standard [Link]
Standard [Link]
Easy [Link]
Easy [Link]
Summary
We have shown you
The structure of a Django project
How models represent data in Django applications
How data can be stored and queried via model
instances
How data can be managed through a dynamic
admin interface
How functionality is represent by views, each
associated
with URLs that match a given pattern
How views render a response using a template
Thank You