《Django JavaScript Integration - AJAX and jQuery》由会员上传分享,免费在线阅读,更多相关内容在学术论文-天天文库。
DjangoJavaScriptIntegration:AJAXandjQueryDevelopAJAXapplicationsusingDjangoandjQueryJonathanHaywardBIRMINGHAM-MUMBAI DjangoJavaScriptIntegration:AJAXandjQueryCopyright©2010PacktPublishingAllrightsreserved.Nopartofthisbookmaybereproduced,storedinaretrievalsystem,ortransmittedinanyformorbyanymeans,withoutthepriorwrittenpermissionofthepublisher,exceptinthecaseofbriefquotationsembeddedincriticalarticlesorreviews.Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyoftheinformationpresented.However,theinformationcontainedinthisbookissoldwithoutwarranty,eitherexpressorimplied.Neithertheauthor,norPacktPublishing,anditsdealersanddistributorswillbeheldliableforanydamagescausedorallegedtobecauseddirectlyorindirectlybythisbook.PacktPublishinghasendeavoredtoprovidetrademarkinformationaboutallofthecompaniesandproductsmentionedinthisbookbytheappropriateuseofcapitals.However,PacktPublishingcannotguaranteetheaccuracyofthisinformation.Firstpublished:January2011ProductionReference:1291210PublishedbyPacktPublishingLtd.32LincolnRoadOltonBirmingham,B276PA,UK.ISBN978-1-849510-34-9www.packtpub.comCoverImagebyVinayakChittar(vinayak.chittar@gmail.com) CreditsAuthorEditorialTeamLeaderJonathanHaywardAksharaAwareReviewersProjectTeamLeaderJakeKronikaAshwinShettyMichaelSzulProjectCoordinatorAcquisitionEditorJoelGoveyaStevenWildingProofreaderDevelopmentEditorSandraHopperMaitreyaBhakalProductionCoordinatorTechnicalEditorsAparnaBhagatVanjeetD'souzaConradSardinhaCoverWorkAparnaBhagatIndexersHemanginiBariMonicaAjmeraMehta ForewordInthisbook,wewillbeexploringDjangoJavaScriptintegrationandbuildanAjaxapplicationusingjQuery.WewillbuildaWeb2.0intranetemployeedirectory,andwewillaimforasolutionthatisPythonicinmorewaysthanone.Webdevelopmentthatismore"Pythonic"thanjustPythonThisbookisintendedtobeabookabouthowtodowebdevelopmentinthespiritofPython++.Theterm"Python++"asweuseithereisnottheusual"Pythonisgreat,"evenifthatmayalsobeouropinion,butamoredirectanalogytoC++.WhentheeffortwasmadetoimprovetheClanguage,thebasickindofimprovementattemptedwastoexpandandbroadenthecorelanguage.ItisnoaccidentthatStroustrup'sTheC++ProgrammingLanguageisfarlongerthanKerniganandRitchie'sTheCProgrammingLanguage.Thelatterisasmallbookdescribingasmallcorelanguage,whiletheformerisalargebookmadelargebythelargecorelanguageitdescribes.TheanalogyintendedbyPython++issomewhatloosehere,andspecificallydoesnotincludealarge,orevenasmall,expansionofthecorelanguage.Itispossibletotinkerwiththecorelanguage—easy_extendletsyouextendPythontoincludeado-whileloop(wherethetestconditionisfirstevaluatedattheend,notthebeginning)—oraddprimitivesyntaxsoyoucandothingslikeifremote_ipin10.0.0.0:,butthisisalmostbesidethepoint.TherealpossibilitiesforexpandingPythondonotneedtoradicallyexpandthecorelanguage,orchangethecorelanguageatall.Django(http://www.djangoproject.com/)isnotageneralpurposeenhancementtoPython:ifyouareautomatingsystemadministrationtasks,forinstance,youveryprobablyhavenoreasontouseDjango.Butforalimitedproblemdomain,namelycertainkindsofwebdevelopment,DjangoismorePythonicthanPython.Python'scgimoduleisgoodforsomekindsofsmallandsimpletasks,butifyouaregoingtomakeaserious,large-scalewebapplicationwithmanystandardfunctions,usingPythoncorelanguage+Pythonstandardlibrary+DjangoisafundamentallymorePythonicapproachthanjustPythoncorelanguage+Pythonstandardlibraryalone. OnStackOverflow,someoneaskedthequestion,"HaveyouconsideredusingDjangoandfoundgoodreasonsnotto?"Therewerevariousanswers,buttheanswerwiththemost"up"votesbyfarsaid,"Iamanhonestguy,andtheclientwantedtochargebythehour.TherewasnowayDjangowasgoingtomakemeenoughmoney."DjangoitselfisnotthelimittoPython++.Pinax(http://pinaxproject.com/)isbuiltontopofDjangoandoffersa"moreDjangothanDjango"platformtobuildasocialnetwork.Satchmo(http://satchmoproject.com/)isalso"moreDjangothanDjango"foranothernarrowerfocus:e-commercewebshops.AndthereareotherplatformsbuiltonDjango;itistimewellspenttosearchthePythonPackageIndex(http://pypi.python.org/pypi)forDjangotoseewhatisalreadyavailable.Inthistextwewilloftenuse"Django"asashorthandforeitherbasicDjangooranyofthemanygoodtoolsbuiltontopofDjango.Dependingonwhatyouaretryingtodo,itmaybethatthebulkofthePythonworkinDjangoisresolvedsurprisinglyquickly:youcanbuildandbrandaPinaxsocialnetworkbydoinglittlemorethanoverridingtheCSSandaddingimages.ThisbookwilladdressthePythonsideandtrytogiveasolidbasisforprogrammingPythonforDjango,workingwiththetemplates,andsoon,butthatproblemcanoftenbesolvedsocleanlythatmostoftheworkthatremainsisstylingandAjax.DjangoanditstemplatingengineBeforefurtherexploringtechnicaldetails,itwouldbeworthtakingalookattheopinionsandphilosophybehindtheDjangotemplatinglanguage,becauseanunderstandableapproachof,"Oh,it'sageneralpurposeprogramminglanguageveryslightlyadaptedfortemplating,"isarecipeforneedlessfrustrationand"isarecipeforneedlessfrustrationandpain.TheDjangodevelopersthemselvesacknowledgethattheiropinionsinthetemplatinglanguageareonejustopinioninanareawheredifferentpeoplehavedifferentopinions,andyouarewelcometodisagreewiththemifyouwant.Ifyoudon'tlikethetemplatingsystemthatDjangocomeswith,Djangoisdesignedtoletyouuseanother.Butitisworthunderstandingwhatexactlythephilosophybehindthetemplatinglanguageis;evenifthisisnottheonlyphilosophyonecoulduse,itiscarefullythoughtout. TheDjangotemplatinglanguageisintendedtofostertheseparationofpresentationandlogic.Initsdesigndecisions,bothlargeandsmall,theDjango'stemplatingengineisoptimizedprimarilyfordesignerstousefordesigning,ratherthanprogrammerstouseforprogramming,anditslimitationsarealmostascarefullychosenasthefeaturesitprovides.UnlikeASP,JSP,andPHP,itisnotaprogramminglanguageinterspersedwithHTML.Itprovidesenoughpowerforpresentation,isintendednottoprovideenoughpowertodoseriousprogrammingworkwhereitdoesn'tbelong(intheDjangoopinion),andissimpleenoughthatsomenon-programmerscanpickitupinaday.Foraprogrammer,thedifficultyoflearningthetemplatingbasicsiscomparabletothedifficultyofsimpleHTMLorSQL:itissimple,andagoodbiteasiertolearnthanwrappingyourarmsaroundaregularprogramminglanguage.ItislikelythatthereareanumberofDjangoprogrammersouttherewhostartedbyasking,"Whydoesn'tthetemplatinglanguagejustletyoumixPythonandHTML?"andafterplayingwithit,foundthemselvessaying,"Thisisn'twhatIwouldhavecomeupwithmyself,butIreally,reallylikeit."Additionalbenefitsincludeitbeingfast(mostoftheworkisdonebyasingleregularexpressioncall,andthefounderstalkaboutdisablingcachingbecauseitcouldn'tkeepupwiththetemplaterenderingengine'sspeed),secure(itisdesignedsothatitcanbeusedbyuntrusteddesignerswithoutallowingamaliciousdesignertoexecutearbitrarycode),andversatileenoughtogeneratewhatevertextformatyouwant:plaintext,HTML,XML,XHTML,JSON,JavaScript,CSV,ReStructuredText,andsoon.WewillbeusingittogeneratewebpagesandJSON,butDjango'stemplatinglanguageisageneral-purposetexttemplatingsolution.Whatwewilldointhisbook—buildingaWeb2.0intranetemployeephotodirectoryManybookswillteachyouanewtechnologybywalkingthroughasampleproject.Thisbookisnodifferent,butthesampleprojectisnotatoy:itisawalkthroughmakingareal,liveWeb2.0intranetemployeephotodirectorythatyoucancustomizetoyourorganization'sneeds.Thisissomethingthatisbothuseful,andwillgiveusatourofthepotentialfordevelopingAjaxapplicationsusingDjangoontheserversideandjQueryontheclientside.-JonathanHayward AbouttheAuthorJonathanHaywardasachildranked7thinanationwidemathcontest,andlaterprogrammedavideogameonhiscalculator.Heholdsmaster'sdegreesinbridgingmathematicsandcomputerscience(UIUC),andphilosophyandtheology(Cambridge).JonathanhaslivedintheU.S.,Malaysia,France,andEngland,andhasstudiedwelloveradozendialectsandlanguages.Hewearsthehatsofauthor,philosopher,theologian,artist,poet,wayfarer,philologist,inventor,andaskilledwebdeveloperwhoholdsadeepinterestinthehumansideofcomputing.Hehasawebsiteshowcasinghisworksathttp://JonathansCorner.comandcanbereachedviae-mailatjonathan.hayward@pobox.com.Iwouldliketothankmyparents,JohnandLinda,wholovelearningandtaughtmefaith,mybrothers,Matthew,KirkandJoe,myparish,St.InnocentofMoscow,forawealthofsupport.IwouldalsoliketothanktheeditorialteamatPackt:StevenWilding,whohelpedmecomeupwiththebookideainthefirstplace,VedPrakashJha,whohelpedseeittocompletion,andJoelGoyeva,whohelpedmewithinnumerablelogisticsalongtheway.And,ofcourse,thereviewersJakeKronikaandMichaelSzul,whoofferedaninvaluablesharpening.TheDjangolist,django-users@googlegroups.com,isworthitsweightingold.IwouldliketothankDanielRoseman,AlexRobbins,DanHarris,KarenTracey,OlegLokalma,MarkLinsey,JeffGreen,ElijahRutschman,BrianNeal,EuanGoddard,SævarÖfjörð,"Ringemup",BenAtkin,TomEvans,SamLai,andPrestonHolmes.Authorshavetoleavesomebodyoutwhodeservestobementioned;that'sjustpartoftheterritory.ButIwouldliketothankonepersoninparticular:thereader.You'rereallythereasonthebookishere,andyou'vechosentoinvestsomemoneyinabookandsometimeinfascinatingtechnologiesandletmehelpyoualongtheway.Thankyousomuch. AbouttheReviewersJakeKronika,awebdesigneranddeveloperwithoverfifteenyearsofexperience,bringstothisbookastrongbackgroundinfrontenddevelopmentwithJavaScriptandAJAX,aswellasexposuretotheDjangoframework.HavingearnedaBachelorsofSciencedegreeinComputerSciencefromIllinoisWesleyanUniversityin2005,withaminorinBusinessAdministration,JakewentontobecomeSeniorUserInterface(UI)SpecialistforImaginaryLandscape,LLC,asmallwebdevelopmentfirminRavenswood,onthenorthsideofChicago.Inthisrole,thefoundationsofhisstrengthsinCascadingStyleSheets(CSS)andJavaScript(JS)werebuilt,aswellasextensiveuseofPythonandtheDjangoFramework.Fromthere,JakewentontoworkfortheSun-TimesNewsGroup,owneroftheChicagoSun-TimesandnumeroussuburbannewspapersinChicagoland.ItwasinthisrolethathewasinitiallyexposedandrapidlybecameanexpertwiththejQueryframeworkforJS.FollowinganintermediatepositionasTechnologyConsultantwithObjectiveArts,Inc,JakehasworkedasUIPrototyperforJPMorganChasesinceFebruary2010.Since1999,hehasalsooperatedGridlineDesign&Development,asoleproprietorshipforwebdesign,development,andadministration.Iwouldliketothankmywife,Veronica,forherongoingsupport.SheandmytwinchildrenMykaelaandKadenprovideallthejoyIcouldwantinthisworld. MichaelSzulhasdesignedanddevelopedsoftwareapplicationsforFortune500companies,includingAIGandPraxair,since1998.Later,heservedasaseniorsoftwareengineerforthetechnologydivisionofPerformanceMediaGroup,contributingtotheirfastgrowthandsuccess,includingplacementontheInc.5000.Szul'sexpertiseinsocialsoftwaredevelopmentledtoalateralmovewithinthecompanytobecomethedirectorofdevelopmentfortheirtravelsocialnetwork.HeevenbuiltsuccessfulsocialsoftwareforcompaniessuchasAppleVacationsandCondeNaste'sGourmetMagazine.AsapartneratBarbellaDigital,Inc.,hecurrentlydesignsanddevelopsenterprise-levelworkflowsystemsandmobileapplicationsforeducationalinstitutions. www.PacktPub.comSupportfiles,eBooks,discountoffersandmoreYoumightwanttovisitwww.PacktPub.comforsupportfilesanddownloadsrelatedtoyourbook.DidyouknowthatPacktofferseBookversionsofeverybookpublished,withPDFandePubfilesavailable?YoucanupgradetotheeBookversionatwww.PacktPub.comandasaprintbookcustomer,youareentitledtoadiscountontheeBookcopy.Getintouchwithusatservice@packtpub.comformoredetails.Atwww.PacktPub.com,youcanalsoreadacollectionoffreetechnicalarticles,signupforarangeoffreenewslettersandreceiveexclusivediscountsandoffersonPacktbooksandeBooks.http://PacktLib.PacktPub.comDoyouneedinstantsolutionstoyourITquestions?PacktLibisPackt'sonlinedigitalbooklibrary.Here,youcanaccess,readandsearchacrossPackt'sentirelibraryofbooks.WhySubscribe?•FullysearchableacrosseverybookpublishedbyPackt•Copyandpaste,printandbookmarkcontent•OndemandandaccessibleviawebbrowserFreeAccessforPacktaccountholdersIfyouhaveanaccountwithPacktatwww.PacktPub.com,youcanusethistoaccessPacktLibtodayandviewnineentirelyfreebooks.Simplyuseyourlogincredentialsforimmediateaccess. TableofContentsPreface1Chapter1:jQueryandAjaxIntegrationinDjango7AjaxandtheXMLHttpRequestobject8Humanspeech:Anoverlaidfunction8Ajax:Anotheroverlaidfunction8ThetechnologiesAjaxisoverlaidon9JavaScript9XMLHttpRequest14Methods14Properties15HTML/XHTML17XML18JSON18CSS19TheDOM19iframesandotherAjaxvariations20JavaScript/AjaxLibraries21Server-sidetechnologies21AlookatDjango21Djangotemplatingkickstart22AmorecompleteglimpseatDjangotemplating23SettingJavaScriptandotherstaticcontentinplace32Summary33Chapter2:jQuery—theMostCommonJavaScriptFramework35jQueryandbasicAjax36jQueryAjaxfacilities39$.ajax()39context40data42 TableofContentsdataFilter43dataType43error(XMLHttpRequest,textStatus,errorThrown)44success(data,textStatus,XMLHttpRequest)44type44url44$.aj0axSetup()45Sampleinvocation45$.get()and$.post()45.load()46jQueryasavirtualhigher-levellanguage48Theselectors48Aclosure-basedexampletomeasureclockskew52Casestudy:Amorein-depthapplication56Chapter3:ValidatingFormInputontheServerSide56Chapter4:Server-sideDatabaseSearchwithAjax56Chapter5:SigningUpandLoggingintoaWebsiteUsingAjax57Chapter6:jQueryIn-placeEditingUsingAjax57Chapter7:UsingjQueryUIAutocompleteinDjangoTemplates57Chapter8:DjangoModelForm:aCSSMakeover57Chapter9:DatabaseandSearchHandling57Chapter10:TinkeringAround:Bugfixes,FriendlierPasswordInput,andaDirectoryThatTellsLocalTime58Chapter11:UsabilityforHackers58Appendix:DebuggingHardJavaScriptBugs58Summary58Chapter3:ValidatingFormInputontheServerSide61Thestandardlecture:low-levelvalidation62Matchingregularexpressions62Youcannotguaranteeabsolutelyvaliddata63Validatingcandetect(some)maliciousinput63TheDjangowayofvalidation64Djangogivesyousomethingsforfree64ThestepsinDjango'svalidation65Amoresensibleandcruelty-freeapproachtovalidation66Thingsgetmurkier67Thezero-one-infinityrule:acardinalruleofthumbinusability68AnimprovementonDjango'sadvertisedapproach68Avalidationexample:GPScoordinates70Avoidingerrormessagesthatpointfingersandsay,"You'rewrong!"71[ii] TableofContentsValidationasdemandingthatassumptionsbemet72Old-school:conformtoourU.S.-basedassumptions!72Addingthewrongkindofband-aid74Makingassumptionsanddemandingthatusersconform76Atleastnamesaresimple,right?76EveninASCII,thingskeepgettingmurkier77Bettervalidationmaybelessvalidation78Caveat:Englishissomethingofalinguafranca79Wedon'thavetonegotiatewithpistols80Doingourbesttosolvethewrongproblem:astory81Itreallydoesapplytovalidation82FacebookandLinkedInknowsomethingbetter83Summary83Chapter4:Server-sideDatabaseSearchwithAjax85Searchingontheclientsideandserverside86HandlingdatabasesthroughDjangomodels86Modelsforanintranetemployeephotodirectory87Searchingourdatabase95AtourofDjangopersistencefacilities100Summary103Chapter5:SigningUpandLoggingintoaWebsiteUsingAjax105admin.py:administrativefunctionscalledonce107functions.py:project-specificfunctions,includingour@ajax_login_requireddecorator107views.py:functionsthatrenderwebpages108style.css:basicstylingforusability113search.html:atemplateforclient-sideAjax114TheDjangoadmininterface122Summary124Chapter6:jQueryIn-placeEditingUsingAjax125Includingaplugin127Howtomakepagesmoreresponsive127Atemplatehandlingtheclient-siderequirements128Thebulkoftheprofile132Whitespaceanddelivery133Page-specificJavaScript136Supportontheserverside137Summary139[iii] TableofContentsChapter7:UsingjQueryUIAutocompleteinDjangoTemplates141Addingautocomplete:firstattempt142Progressiveenhancement,abestpractice142Areal-worldworkaround146"Interest-basednegotiation":apowertoolforproblemsolvingwhenplanAdoesn'twork146Afirstworkaround148BoilerplatecodefromjQueryUIdocumentation154TurningonAjaxbehavior(ortryingto)156Codeontheserverside156Refiningoursolutionfurther159Summary163Chapter8:DjangoModelForm:aCSSMakeover165"Hello,world!"inModelForm165Expandingandcustomizingtheexample168CustomizingModelFormpages'appearance170GoingunderModelForm'shood182Anexcellent"stupid"question:where'sthee-mailslot?184Summary187Chapter9:DatabaseandSearchHandling189MovingforwardtoanAHAHsolution189DjangotemplatesforsimpleAHAH192Templatingforalistofsearchresults192Templateforanindividualprofile195Viewsontheserverside202Tellingiftheuserisloggedin202Aviewtosupportdeletion202TheAHAHviewtoloadprofiles203HelperfunctionsfortheAHAHviewforsearching204Anupdatedmodel206AnAHAHserver-sidesearchfunction207Handlingtheclient-side:Atemplateforthemainpage209CSSforstylingthedirectory232Ourupdatedurlpatterns241Summary241Chapter10:TinkeringAround:Bugfixes,FriendlierPasswordInput,andaDirectoryThatTellsLocalTime243Minortweaksandbugfixes243Settingadefaultnameof"(Insertnamehere)"244EliminatingBorgbehavior244[iv] TableofContentsConfusingjQuery'sload()withhtml()245Preventingdisplayofdeletedinstances246Addingafavicon.ico249Handlingpasswordinputinaslightlydifferentway250Adirectorythatincludeslocaltimekeeping252Summary260Chapter11:UsabilityforHackers261Usabilitybeginswithanthropology…andDjangohackershaveagoodstartonanthropology262Anthropologicalusabilitytechniques263Anintroductoryexample:cardsorting263Focusgroups:cargocultresearchforusability265Anthropologicalobservation:thebedrockofusability265Morethanonewaytoseethesamesituation266Applyingthisfoundationtousability268It'sjustlike(hard)debugging271Lessonsfromotherareas272Livecross-culturalencounters272History273Oldbooksandliterature274Thelastotherarea:whateveryouhave277Understandingtheuser278Alessonfromoptimization278What'swrongwithscratchinganitch,oryouarenotyouruser279Worstpracticesfromthejargonfile279Pythonandusability280It'snotallaboutthecomputer!280Whattodointheconcrete282Furtherreading283Summary284Appendix:DebuggingHardJavaScriptBugs285"JustfiddlingwithFirebug"isconsideredharmful285Cargocultdebuggingatyourfingertips285Thescientificmethodofdebugging286Exhaustingyourselfbybarkingupthewrongtree287Thehumbledebugger289Thevalueoftakingabreak289Twomajorbenefitstoaskingforhelp290[v] TableofContentsFirebugandChromedevelopertools290Thebasicsacrossbrowsers290ZeroinginonChrome293Summary298Index299[vi] PrefaceYouwanttocreateanAJAXapplication.WhywouldyouuseDjango?WhywouldyouusejQuery?Whywouldyouusebothtogether?EnterDjangoJavaScriptIntegration:AJAXandjQuery—yourcomprehensiveanswertoallthesequestionsandtheonlyextensive,practical,andhands-onguidetodevelopinganyAJAXapplicationwithDjangoandjQuery.GonearethedayswhenyouusedtolamentoverthelackofofficialdocumentationonAJAXwithDjango.ThisbookwillteachyouexactlywhyDjangoiscalledThewebframeworkforperfectionistswithdeadlines,howjQuery—the"writelessdomore"JavaScriptlibrary—ispracticallyavirtualhigher-levellanguage,andwhytheybothdeservetobeintegratedwithAJAX.Thishands-on-guideshowsyouhowtoputDjangoandjQuerytogetherintheprocessofcreatinganAJAXapplication.Inthisbook,theyarebroughttogetherinareal-worldscenario,withattentiontousability,tobuildanddevelopanAJAXapplication.ThefirsttwochaptersprovideashortandnecessaryintroductiontotheworldofDjango,jQuery,andAJAX;theremainingchaptersarebasedonacasestudythatwillmakeyourealizetheimmensepotentialandbenefitsofintegratingDjangoandjQuerywithyourAJAXapplication.Bythetimeyouaredonewiththisbook,you'llbedevelopingyourAJAXapplicationswithDjangoandjQueryinlesstimethanyoucansay"integrate".YouwillcoverthebasicsofAJAX;usejQuery,themostcommonJavaScriptlibrary,ontheclientside,andlearnformvalidationwithaneyetowardsusability,buildthingswithDjangoontheserverside,handleloginandauthenticationviaDjango-basedAJAX,andthendipintotherichjQuerypluginecosystemtobuildin-placeeditingintoyourpages. PrefaceYouwilladdauto-completefunctionalitycourtesyofjQueryUI,easilybuildformswithDjangoModelForm,andthenlookataclient-sidesearchimplementationthatcanlookthingsupwithoutnetworkaccessafterinitialdownload.Youwilllearntoimplementasimple,expandableundosystem,andoffermorefull-bloodedaccountmanagement,tinker,fixsomebugs,offeramoreusablewaytohandlepasswordinput,addlocaltimesupportforpeoplewhoarenotinyourtimezone,lookatusability,andfinallytakealookatdebugging.Afterworkingthroughthisbook,youwillhavebothanAJAXapplication:aWeb2.0employeeintranetphotodirectory,andwithitadeepunderstandingthatyoucanusetocustomize,extend,andfurtherdevelopitinyourorganization.WhatthisbookcoversThisbookcoversDjangoJavaScriptintegrationandbuildinganAjaxapplicationwithDjangoontheserversideandjQueryontheclientside.Itprovidesfirstanoverview,thenafirstAjaxapplication,andintroducesjQuery;discussesformvalidation,server-sidedatabasesearch;Ajaxloginfacilities;jQueryin-placeeditingandautocomplete,DjangoModelform,andhowtogiveauto-generatedformsatransformationalCSSmakeover.Italsodiscussesclient-sidefunctionality,customization,andfurtherdevelopmentwithtinkeringandaddedfeatures,beforeagrandfinaleexploringusability,andanappendixondebugginghardJavaScriptbugs.Chapter1,jQueryandAjaxIntegrationinDjangolaysasolidfoundationandintroducesyoutotheworkingpiecesofDjangoAjaxtobeexploredintherestofthebook.Chapter2,jQuery—theMostCommonJavaScriptFrameworkexploresthe"higher-level"wayofdoingthingsinjQuery.YouwilllearnhowjQueryisnotPythonanddoesnotlooklikePython,buthowthereissomething"Pythonicinspirit"abouthowitworks.Chapter3,ValidatingFormInputontheServerSidewillteachyouhowtosendanAjaxrequesttotheserverviajQuery,andvalidateitontheserversidebasedontheprinciplethatallinputisguiltyuntilproveninnocentofbeingmalicious,malformed,incomplete,orotherwiseinvalid.Chapter4,Server-sideDatabaseSearchwithAjaxlooksbothatthemeritsofhandlingsearchingandotherbackendfunctionswiththefullpowerofabackendenvironment,andexploreswhy,ontheclientside,youshouldworkhardtobeaslazyaspossibleindoingnetwork-relatedwork.[2] PrefaceChapter5,Signing-upandLoggingintoaWebsiteUsingAjaxintroducesDjangoauthenticationfacilitiesandaccountmanagementandincludesbothserver-sideandclient-sidecode.Chapter6,jQueryIn-placeEditingUsingAjaxgoesfromabasicfoundationtoacontinuingpracticalapplication.ItwillshowawaytousejQuerytomakeanin-placereplacementofatablethatallowsin-placeediting,whichcommunicateswiththeserverinthebackground,addingpersistencetochanges.Chapter7,UsingjQueryUIAutocompleteinDjangoTemplatestellsyouwhatyouneedontheclientsideandserversidetogetautocompleteworkingwithjQueryUI.Italsoincludescreativeproblemsolvingwhensomethinggoeswrong.ThischapterwilltellyouwhyitisnotuncommonforprogrammerstowritepluginstheirfirstdaydoingjQuery.Chapter8,DjangoModelForm:aCSSMakeoverexploresDjangoModelFormandhowtouseit.Chapter9,DatabaseandSearchHandlingcoversallthebasesforasimple,AHAHsolution.Inadditiontoshowing"lazy"bestpractices,italsoshowcasesaJavaScriptin-memorydatabase,withanapplicationdesigned,atthedeveloper'spreference,toeitheralwaysperformlazyhandlingofsearchandotherrequests,orstartloadinganin-memorydatabaseandfallingbacktolazyhandlinguntilthein-memorydatabaseisavailable.Chapter10,TinkeringAround:Bugfixes,FriendlierPasswordInput,andaDirectoryThatTellsLocalTimecoverssometinkeringandtweaks,andbugfixesalongthewayChapter11,UsabilityforHackersstepsbackfromyourapplicationandtakesalookatusabilityandthebedrockcompetencieshackerscanleveragetodousability.Appendix,DebuggingHardJavaScriptBugslooksatthestateofmindthatisneededtodebugdifficultbugs.WhatyouneedforthisbookThisbookassumesabroadtechnicalmaturityandanabilitytolearnandintegratedifferentskills.IthelpstobeaPythonistawiththeusualstrengthsthatcomewithPython,andknowledgeoftheWeb.Abasicunderstandingof,ortheabilitytolearn,DjangoandJavaScriptwillbehelpful.Ifyou'reagoodgeneralistprogrammerwhowantstolearnDjangoJavaScriptintegration,thisbookisforyou.[3] PrefaceWhothisbookisforThisbookisforpeoplelookingtointegrateAJAX/JavaScriptfunctionalityintotheirwebapplications.ItisforDjangouserswhoarelookingtoeasilyintegrateAJAXfeaturesintotheirapplications.Conversely,itwillalsobeapricelesscompanionforusersfamiliarwithDjangoandjQuerywhoarelookingtointegratethemintheirAJAXapplications.AworkingknowledgeofDjangoandbasicfamiliaritywithAJAXandjQueryareassumed.ConventionsInthisbook,youwillfindanumberofstylesoftextthatdistinguishbetweendifferentkindsofinformation.Herearesomeexamplesofthesestyles,andanexplanationoftheirmeaning.Codewordsintextareshownasfollows:"YoucanoverridetheemptystringbysettingTEMPLATE_STRING_IF_INVALIDinyoursettings.pyfile".Ablockofcodeissetasfollows:functionouter(){result=0;for(i=0;i<100;++i){result+=inner(i);}returnresult}Whenwewishtodrawyourattentiontoaparticularpartofacodeblock,therelevantlinesoritemsaresetinbold:defajax_profile(request,id):entity=directory.models.Entity.objects.filter(id=int(id))[0]ifentity.is_invisible:returnHttpResponse(u'
EverythingthereisonlineaboutW3islinkeddirectlyorindirectlytothisdocument,includingan GreetingsfromtheDjangotemplatingengine!…Atthetimeofthiswriting,HTML5istakingshapebutisnot"outinthewild",andsotherearenoreportsofhowtheshoefeelsafterthepublichaswornitforawhile.Codeinthisbook,wherepossible,willbewritteninXHTML1.0Strict.Dependingonyoursituation,thismayormaynotbetherightdecisionforyou;ifyouareworkingwithanexistingproject,therightHTML/XHTMLisoftentheonethatmaintainsconsistencywithintheproject.[17] jQueryandAjaxIntegrationinDjangoXMLeXtensibleMarkupLanguage(XML)istiedtoanattempttocleanupearlyHTML.Atleastinearliestforms,HTMLwasablacksheepamongspecificmarkuplanguagesderivedfromthegeneralizedandquiteheavyStandardGeneralizedMarkupLanguage(SGML).Forgivingwebbrowsersmeant,inpart,thatearlywebhobbyistscouldwriteterriblemarkupanditwouldstilldisplaywellinabrowser.Theamountofterriblemarkuponthewebwasnotjustanissueforpurists;itmeantthatmakingaparserthatcouldmakesenseofearly"WildWest"webpagesingeneralwasanearlyimpossibletask.XMLisvastlysimplifiedfromSGML,butitprovidesagenericspacewhereanHTMLvariant,XHTML,couldpickuptheworkdonebyHTMLbutnotpresentparserswithunpredictabletagsoup.XHTMLcouldbedescribedasHTMLbroughtbackintothefold,stillgoodfordoingwebdevelopment,butwithoutmakingmachineinterpretationsuchahopelesscause.WhereearlyHTMLwasdevelopedwithbrowsersthatweremeanttobeforgiving,XMLrequesteddraconianerrorhandling,andvalidatedXMLorXHTMLdocumentsaredocumentsthatcanbeparsedinasensibleway.XMLworksforexchanginginformation,anditworkswheremanyofitspredecessorshadfailed:itprovidesinteroperabilitybetweendifferentsystemsafteralonghistoryoffailedattemptsatautomatingB2Bcommunicationandfailedattemptsatautomatedconversionbetweentextdataformats.Notwithstandingthis,itisaheavyandverbosesolution,withabureaucraticambiance,comparedinparticulartoalean,meanJSON.XML-basedapproachestodatastorageandcommunicationareincreasinglycritiquedindiscussionsontheweb.IfyouhaveareasonablechoicebetweenXMLandJSON,wesuggestthatyouseriouslyconsiderJSON.JSONJavaScriptObjectNotation(JSON)isabrilliantlysimpleidea.WhileformatslikeXML,ReStructuredText,andsoonsharetheassumptionthat"ifyou'regoingtoparsethisfromyourlanguage,yourlanguagewillneedtohaveaparseradded,"JSONsimplytakesadvantageofhowanobjectwouldbespecifiedinJavaScript,andclarifiesacoupleofminorpointstomakeJSONconceptuallysimplerandcross-browserfriendly.JSONisclear,simple,andconciseenoughthatnotonlyisitaformatofchoiceforJavaScript,butitisgainingtractioninotherlanguages,anditisbeingusedforcommunicationbetweenlanguagesthatneeda(simple,added)parsertoparseJSON.Theotherlanguagescan'tuseeval()tosimplyrunJSON,andinJavaScriptyoushouldhaveJSONcheckedtomakesureitdoesnotcontainmaliciousJavaScriptyoushouldnoteval().However,JSONisturningouttohaveamuchbroaderimpactthantheinitial"incommunicatingwithJavaScript,justgiveitcodetodeclaretheobjectbeingcommunicatedthatcansimplybeevaluatedtoconstructtheobject."[18] Chapter1CSSCascadingStyleSheets(CSS)mayhaveintroducedsomenewpossibilitiesforpresentation,butquitealotofpresentationwasalreadypossiblebeforehand.CSSdidnotsomuchaddstylingcapabilities,asitaddedgoodengineeringtostyling(goodengineeringistheessenceof"separatingpresentationfromcontent"),andmakethecombinationofsemanticmarkupandattractiveappearanceafarmoreattainablegoal.Itallowsparlortrickssuchasin-placerebrandingofwebsites:makingchangesinimagesandchangingonestylesheetis,atleastinprinciple,enoughtoreskinanextensivewebsitewithouttouchingasinglecharacterofitsHTML/XHTMLmarkup.InAjax,asfortherestoftheweb,thepreferredpracticeistousesemantic,structuralmarkup,andthenaddstylesinastylesheet(notinline)sothataparticularelement,optionallybelongingtotherightclassorgiventherightID,willhavethedesiredappearance.Tablesarenotdeprecatedbutshouldbeusedforsemanticpresentationoftabulardatawhereitmakessensetousenotonlyatdbutathaswell.Whatisdiscouragedisusingthesideeffectthattablescanpositioncontentthatisnot,semanticallyspeaking,tabulardata.TheDOMAsfarasdirecthumanbrowsingisconcerned,HTMLandassociatedtechnologiesarevehiclestodeliverapickledDocumentObjectModel(DOM),andnothingmore.Inthisrespect,HTMLisameanstoanend:theDOMisthe"deserializedobject,"orbetter,the"liveform"ofwhatwereallydelivertopeople.HTMLmayhelpprovideacompleteblueprint,andthe"completeblueprint"isameanstothe"fullyrealizedbuilding."ThisiswhysolvingAjaxproblemsonthelevelofHTMLtextarelikeansweringthewrongquestion,oratleastsolvingaproblemonthewronglevel.Itislikedecidingthatyouwantapaintinghungonawallofabuilding,andthengoingaboutgettingitbyaddingthepaintingtotheblueprintandaskingconstructionpersonneltoimplementthespecifiedchange.Itmaybebettertohangthepaintingonthewalldirectly,asisdoneinAjaxDOMmanipulations.document.write()anddocument.getElementById().innerHTML()stillhaveaplaceinwebdevelopment.Itisasensibleoptimizationtowantastatic,cacheableHTML/XHTMLfileincludethatwillonlybedownloadedonceintheusualmulti-pagevisit.AJavaScriptincludewithaseriesofdocument.write()maybetheleastShanghaiingyoucandototechnologiesandstillachievethatgoal.ButthisisnotAjax;itisbarelyJavaScript,andthisisnotwhereweshouldbegettingourbearings.InAjax,aseriousalternativetothiskindofsolutionforalteringpartofawebpageiswiththeDOM.Asthebookprogresses,wewillexploreAjaxdevelopmentthatworkswiththeDOM.[19] jQueryandAjaxIntegrationinDjangoiframesandotherAjaxvariationsAjaxincludesseveralvariations;Cometforinstance,isavariationonstandardAjaxinwhicheitheranXMLHttpRequestobject'sconnectiontoaserveriskeptopenandstreamingindefinitely,oranewconnectionisopenedwheneveranoldoneisclosed,creatinganAjaxenvironmentinwhichtheserveraswellastheclientcanpushmaterial.Thisisused,forinstance,insomeinstantmessagingimplementations.OnemuchmoreessentialAjaxvariationhastodowithloadingdocumentsintoseamlesslyintegratediframesinsteadofmakingDOMmanipulationstoasingle,frame-freewebpage.IfyouclickaroundonthepageforaGmailaccount,youwillseepartialpagerefreshesthatlookconsistentwithAjaxDOMmanipulations:whathappenswhenyouclickonComposeMail,orafilter,oramessagesubject,looksverymuchlikeanAjaxupdatewheretheGmailwebapplicationtalkswiththeserverifitneedsto,andthenupdatestheDOMinaccordancewithyourclicks.However,thereisoneimportantdifferencebetweenGmail'sbehaviorandasimilarAjaxclonethatupdatestheDOMforoneframelesswebpage:whathappenswhenyouclickthebrowser"Back"button.Normally,ifyouclickonalink,youtriggeranAjaxeventbutnotawholepagerefresh,andAjaxoptionallycommunicateswithaserverandupdatessomepartoftheDOM.Thisdoesnotregisterinthebrowser'shistory,andhittingtheBackbuttonwouldnotsimplyresetthelastAjaxpartialpageupdate.IfyoumadeanAjaxcloneofGmailthatusedDOMmanipulationsinsteadofseamlesslyintegratediframes,therewouldbeoneimportantdifferenceinusingtheclone:hittingBackwoulddofarmorethanreversethelastDOMmanipulation.Itwouldtakeyoubacktotheloginorloadscreen.InGmail,thebrowser'sBackbuttonworkswithsurgicalaccuracy,andthereasonitcandosomethingmuchbetterthantakeyoubacktotheloginscreenisthatGmailiscarefullyimplementedwithiframes,andeverychangethattheBackbuttoncanundoisimplementedbyafreshpageloadinoneoftheseamlesslyintegratediframes.Thatcreatesbrowsinghistory.Forthatmatter,aproofofconcepthasbeencreatedforanAjaxapplicationthatdoesnotuseclient-sidescriptingorprogramming,insteadusing,ontheclientside,asystemofframes/iframes,targets,links,formsubmissions,andmetarefreshtagsinordertoperformpartialpageupdates.WhetherthisvarianttechniquelendsitselftocreatinggracefulalternativestostandardAjaximplementations,orisonlyacuriositymerelylendingitselftoproofsofconcept,itisinprinciplepossibletomakeanAjaxapplicationthatlosesnothingifavisitor'sbrowserhasturnedoffscriptingcompletely.CometandiframesaretwoofmanypossiblevariationsonthebasicAjaxtechnique;whatqualifiesasAjaxismoreamatterofPython-orJavaScript-styleduck-typingthanJava-stylestatictyping."AsynchronousJavaScriptandXML"describesareferenceexamplemorethanastrictdefinition,anditisnotappropriatetosay"if[20] Chapter1youreplaceXMLwithJSONthen,bydefinition,itisn'treallyAjax."Thisisacaseof,"theproofofthepuddingisintheeating,"notwhattechnologiesoreventechniquesareinthekitchen.JavaScript/AjaxLibrariesThisbookadvocatestakingadvantageoflibraries,andasalimitationofscopefocusesonjQuery.Ifyouonlylearnonelibrary,orifyouarestartingwithjustonelibrary,jQueryisagoodchoice,anditiswidelyused.Itispowerful,butitisalsoamucheasierenvironmenttogetstartedinthansomeotherlibraries;inthatway,itissomewhatlikePython.However,itisbestnottoask,"Whichonelibraryisbest?"but"Whichlibraryorlibrariesaretherighttoolsforthisjob?",anditiscommonreal-worldpracticetousemorethanonelibrary,possiblyseveral.JavaScriptlibrariesofferseveraladvantages.Theycanreducechoresandboilerplatecode,significantlylesseningthepainofJavaScript,andprovideamoreuniforminterface.Theycanalsoprovide(forinstance)ready-madewidgets;wewillbeworkingwithajQuerysliderlateroninthisbook.Andonabroadscale,theycanlettheJavaScriptyouwritebehigher-levelandalittlemorePythonic.Server-sidetechnologiesManyofthe"usualsuspects"inclient-sidetechnologieshavebeenmentioned.Thelistofclient-sidetechnologiesisgenerallyconstrainedbywhatisavailableincommonwebbrowsers;thelistofavailableserver-sidetechnologiesisonlyconstrainedbywhatwillworkontheserver,andanygeneral-purposeprogramminglanguagecandothejob.Thequestionontheserverisnot"Whatisavailable?"but"Whichoptionwouldyouchoose?"PythonandDjangomakeanexcellentchoiceofserver-sidetechnology,andwewillworkwiththeminthisbook.AlookatDjangoDjango'sdeveloperscallit"thewebframeworkforperfectionistswithdeadlines,"anditisoneofthemostpopularPythonwebframeworks,perhapsthemostpopular.IncontrasttotheMVCpattern,whichseparatesconcernsintoModel,View,andController,itcouldbedescribedasanMTVpattern,whichseparatesconcernsintoModel,Template,andView.TheModelisaclassthattiesintoanORMwhereinstancescorrespondtorowsinthetablebutactandfeellikePythonobjects.TheTemplateisasystemdesignedtobeeasyfornon-Pythondevelopers(thougheasyforPythonistastoo),andlimitstheextenttowhichHTMLneedstobesprinkledthroughoutthePythonsource.TheViewisafunctionthatrenders,inmostcases,fromatemplate.Let'slookatakickstartexampleofDjangoinaction.[21] jQueryandAjaxIntegrationinDjangoDjangotemplatingkickstartLetusbrieflygothroughhowtoinstallDjango,createasampleproject,andcreateanduseabasictemplatethatcanserveasabasisforfurthertinkering.Djangoinstallationinstructionsareathttp://docs.djangoproject.com/en/dev/intro/install/;forUbuntu,forinstance,youwillwanttorunsudoapt-getinstallpython-django.OnceyouhaveDjangoinstalled,createaprojectnamedsample:django-admin.pystartprojectsampleGointothesampledirectory,andcreatethedirectorytemplates.Enterthetemplatesdirectory.Createatemplatefilenamedindex.htmlcontainingthefollowingtemplate:
{%blockheading%}Hello,world!{%endblockheading%}
{%blockcontent%}