Documente Academic
Documente Profesional
Documente Cultură
with Django!
Instructors:
Steve Levine '11
Maria Rodriguez '11
Geoffrey Thomas '10
sipb-iap-django@mit.edu
http://sipb.mit.edu/iap/django/
Wednesday, January 27th
SIPB IAP 2010
Course Overview
WhatisDjango?
Apps,Models,andViews
URLStructure
Templates
AdminInterface
Forms
Examples/Tutorials
What is Django?
What is Django?
django [jng]
-noun
1.
2.
3.
Funk-tacular Features
projectsorappsarepluggable
objectrelationalmapper:combinestheadvantages
ofhavingadatabasewiththeadvantagesofusing
anobjectorientedprogramminglanguage
databaseallowsforefficientdatastorageand
retrieval
Pythonallowsforcleanerandmorereadablecode
Funk-tacular Features
automaticadmininterfaceoffersthefunctionality
ofadding,editing,anddeletingitemswithina
databaseinagraphical,userfriendlyway
flexibletemplatelanguagethatprovidesawayto
retrievedataanddisplayitonawebpageinits
desiredformat
urldesigniselegantandeasytoread
Controller
View
MVC
Model
Database Layer
MySQL: Database
Amazing Apps
DjangodoesnotworkquitelikePHP,orother
serversidescriptinglanguages
Djangoorganizesyourwebsiteintoapps
Anapprepresentsonecomponentofawebsite
Example:asimplewebpoll,blog,etc.
Appscanbeusedinmultipledifferent
websites/projects(pluggable),andawebsite
canhavemultipleapps
Amazing Apps
Eachapphasitsowndataandwebpagesassociated
withitcalledmodelsandviews,respectively
Example:apollthatletsusersvoteonquestions
Views(differentwebpages):
Pagewithquestions+choices(actualvotingpage)
Statisticspagethatshowspastresults
Models(data):
Pollquestions
Choicesassociatedwitheachquestion
Theactualvotingdata!(setofselectedchoices)
Amazing Apps
Whenyoucreateanapp,Djangomakesafolder,
appname/inyourprojectdirectory
Itcontains,amongsomeotherfiles:
models.py
views.py
urls.py(willbediscussedlater)
Theapplookslikeapackage(ex.,polls.view,
polls.models,etc.)
Models
Magnificent Models
Modelsstoredataforyourapp
Keyformakingdynamicwebsites!
ModelsareimplementedasPythonclasses,in
models.pyfile
AwesomefeatureofDjango:theobjectrelational
mapper
Allowsyoutoaccess/changeadatabase(ex.,
MySQL)justbycallingfunctionsonyourmodels
Magnificent Models
Examplemodels:
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
Magnificent Models
Caneasilycreateinstancesofyourmodel:
p = Poll(question="What's up?",
pub_date=datetime.datetime.now())
Saveittothedatabase:
p.save()
Magnificent Models
Theobjectrelationalmapperevenautomagically
setsupyourMySQLdatabase
Examplegeneratedcode:
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;
Magnificent Models
Examplemethodsandfields:
AlthoughDjangocertainlydoesdoalotforyou,it
helpstoknowabitaboutdatabases
Whendesigningamodel,usefultothinkabout
gooddatabasepractice
Digestible Databases
GoodDatabaseDesigninaNutshell:
1.Groupsofrelatedfieldsbelonginthesametable
2.Newtablesshouldbecreatedfordatafieldsthatare
almostalwaysempty
3.Mostofthetimetheinformationcontainedin
unrelatedfieldswillnotneedtoberetrievedatthe
sametime,sothosegroupsoffieldsshouldbein
separatefieldsasoneanother
Digestible Databases
Example Database:
(a) Patient Table
Patient
ID
Last
Name
First
Name
Room
No.
Patient ID
Medication
Dosage
Instruction
Prescription
ID
Tim
e
Next Admin
Date
W R
S
a
S
u
Views
Vivacious Views
ViewsarePythonfunctionstheymaketheweb
pagesuserssee
Canmakeuseofmodelsforgettingdata
CanuseanythingthatPythonhastooffer!
...andthere'sALOTPythoncando!Makesfor
interestingwebsites
Vivacious Views
Vivacious Views
Viewfunctionstakeasinput:HttpResponseobject
containsusefulinformationabouttheclient,
sessions,etc.
ReturnasoutputHttpResponseobjectbasically
HTMLoutput
Mostoften,viewsdon'tactuallywriteHTMLthey
fillintemplates!(discussedshortly)
Vivacious Views
Exampleview:
Templates
Templates,
Tags,
&
Tricks
Tags:
Ex.variable
{{ poll.question }}
Ex. for-loop
{% for choice in poll.choice_set.all %}
{% endfor %}
Ex. if-statement
{% if patient_list %}
...
{% else %}
...
{% endif %}
DjangostructuresyourwebsiteURL'sinan
interestingway
Recap:theURListhetextyoutypetogettoa
website
FornonDjangowebsites:
http://www.example.com/some/directory/index.php
Referstoafile/some/directory/index.phponthe
server
DifferentinDjango!URL'sareorganizedmore
elegantlyandmoreeasilyunderstandably
Considerthisexample:
http://example.com/articles/2005/03/
URLspecifiesarticledate,notareferencetoa
specificfile
Allowsamorelogicalorganization,thatisless
likelytochangeovertime
OverviewofhowDjangoworks,usingURL's
http://example.com/articles/2009/01/27
URLs
Views
Templates
URLConf
View: polls()
Template: plain
View: articles()
Template: fancy
View: authors()
Template: cute
URLpatternsmaptoViews
Viewsmayusetemplates
TemplatescontainHTML(discussedlater)
ThisputsalayerofabstractionbetweenURL
namesandfiles
Thefileurls.pythatspecifieshowURL'sget
mappedtoviews,usingregularexpressions
Exampleurls.py:
urlpatterns = patterns('',
(r'^articles/2003/$', 'news.views.special_case_2003'),
(r'^articles/(?P<year>\d{4})/$', 'news.views.year_archive'),
(r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/$', 'news.views.month_archive'),
(r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d+)/$', 'news.views.article_detail'),
)
http://example.com/articles/2009/03/14willresult
innews.views.article_detail(request, year='2009',
month='03', day='14')beingcalled
Thesearemostlylikeregularexpressions,which
areoutsideofthescopeofthisclass
Admin Interface
Djangowaswritteninanewsroomenvironment,withaveryclearseparationbetween
contentpublishersandthepublicsite.Sitemanagersusethesystemtoadd
newsstories,events,sportsscores,etc.,andthatcontentisdisplayedonthepublic
site.Djangosolvestheproblemofcreatingaunifiedinterfaceforsite
administratorstoeditcontent.
Theadminisntnecessarilyintendedtobeusedbysitevisitors;itsforsitemanagers.
Reference:http://docs.djangoproject.com/en/dev/intro/tutorial02/
http://docs.djangoproject.com/en/dev/intro/tutorial02/
Forms
Example:
Satisfying Sessions
YoucanusessessionsinDjango,justlikethe
sessionsinPHP
Sessionsallowyoutostorestateacrossdifferent
pagesofyourwebsite
Commonuses:storeloggedinusername,shopping
cartinformation,etc.
Ifyouwritetoasessioninoneview(webpage),it
willbevisibleinallviewsafterwardsaswell
SessionisfoundintheHttpResponseobject
Real-World Apps
MedSched
http://priyaram.scripts.mit.edu/practice/medsched/admin/
Shiny!
http://sjlevine.scripts.mit.edu/django/shiny/
Tutorial: Polling
SettingupDjangothroughScripts:
1.connecttoathena:
>>sshusername@linerva.mit.edu
2.setupscripts
>>addscripts
>>scripts
3.FollowinstructionsfromtheretoinstallDjango
4.connecttoscripts:
>>sshscripts.mit.edu
>>cd~/Scripts
Helpful Commands
Fromprojectfolderrunmysql
typeshowdatabases;toseeyourdatabases
typeuse<database_name>;touseadatabase
typeshowtables;toviewthetablesinthat
database
typedroptable<table_name>;todropatable
Dropaffectedtableseachtimefieldswithinyour
modelschange.
Helpful Commands
>>./manage.pysyncdb
or
>>pythonmanage.pysyncdb
Updatesdatabasetableswheneveryoudrop
tablesoraddapplicationstoINSTALLED_APPSin
settings.py
>>addscripts
>>foreachserverpkillumariapython
Restartsthedevelopmentservertoseeyourchanges.
Handy References
OfficialDjangowebsite:
http://www.djangoproject.org/
Containsanamazingtutorialthatyoushouldfollow
InformationonsettingupDjango
Documentationforvariousclasses,functions,etc.