Python Django Web开发指南


.- .. , . , -<- <. r.. : I 5-P'I.. = !? ,$ , - 7 ; -4 3 j &??; ;/$ pT[J ,.s; 33 .$ 3 ??>, ; ., 1 !I -..: ;; .fZ +* .y !/ 9, :: 3,$-:; z;<: F-5. *-- is,' * 7" 2 ;y - . >, !I ,, , , ,< !:, ::-' ,, *-, /, A . .&... .. . .l"> .iil i .. ,. . - . < ;,.. {- e, f, ,.;. ;< .;+, 2 [ :/ .-.* ?': ; :; . . Jeff Forcier ( Paul Bissex 8 Wesley Chun &A!!@ %% $R%%4nfqHPython&%Django#G&L~3PkmWeb#&k%, *$%%7EH%W Django 1 .Oh~&@~%$~JB%%%~&X, IWUBkfk. &$Qj$12$86+pft2, ptlg@,f;fi, Django Python&&, Django%&: $$I@--qBlog, @%3, ZBK@M&%!, URL, HTTP&%rj8~~H, &&%U%$%@, Photo Gallery, dil&$%! %$j, Liveblog, Pastebin, &!&Django$$@, g!&Django$$%, [$%fi@$f;f&+f?d?J$, 2 %i%j?Django, %HDjango?fXIW, XR, i%, @M~jan~oEH@$, GGoogle App Engine~@Mlljango, @sDjangoq i3 . *RZM7.Python&%Django?n7%, Django Web?fXW+A fl Simplified Chinese edition copyright 0 2009 by Pearson Education Asia Limited and China Machine Press. Original English language title: Python Web Development with Django (ISBN 978-0-13- 235613-8) by Jeff Forcier,Paul Bissex,Wesley Chun, Copyright 0 2009 . All rights reserved. Published by arrangement with the original publisher, Pearson Education, Inc., publishing as Addison-Wesley. *$HGl&+jPearson Education (%&&$Yjfi%B ) &%i%i%&E, %6~$$f+7~~o Django Web?fXfki% (%I Zt% (Jeff, F.), (%) Bk (Paul, B.), (2) Et+$ (Wesley, C.) 3; ~$hl%%i.+. -dl;%: &#I!U!Yjfi+*, 2009.5 (RXAR+&E$X&$) R&E* : Python Web Development with Django ISBN 978-7-1 11-27028-7 $,$$,I&kbfi;Ef (;lLfiti8%EG5Ekfi229 thi'~&%E$ 100037) %E%$3: $%% dL%%dLEPBlGPt?fidE~@ll 2009 +5R %l&%l&EP@I1 186rn1n x 240mm . 18.25EP $& &@$%: ISBN 978-7-1 1 1-27028-7 49.002 ~z&rn~~~+~~s-+~~~~m+~$~ ~~&~zm~m~fiaerne4+2~~, -k'r)-&%i~fR1%~1--~L1~~ *l0fiB@*AmPythonfk4$~fitI:Django$ &fW &%%fi1+Z&i3$$! &i%Django%@, #R~f+~E$~#4~1&~&ES~+~%%~1@&~4+ a 3E%S%#-$Z2&8@aH &&~~~I~~+A~~~, 8~AEi~~~$E4~B~El~WL 88%&9?i2i%&#FEa &%$$$lJ&$$jDebra Williams CauleyM&$$-*fi~A3?$ %&j$$@@&{[1@@$&?% S%&22@+%4i1%&7fBAmAS91k7 B2#-Z%ik&4i1+&TS4+1m0 $$I% &&BHm-t+, &4ilrn@&%%%+iEZ~-* "fii&i%+", KI$~X~X~-*B+$~&~ ZrnDjango%Eo d$$j&4Ofifi$$%iTi!&, Michael Thurston (%3J%+4), Joe Blaylock@ Antonio Cangiano, U&fifi&%$R$%&-E$k.i%Rough Cuts1 @'Tfji%mA, Q%5%4i1, %*Rj-&Efi~Zg, $!i%g&#Matt Brown, Django Helper for Google App Enginei%g@& , E , U&Eric Walstad$REric Evens~n~Grn$$@$~i~$$~ EkG, 4n%?!kfi&4il%~B%-&W3%, &2$~%Z&i3*%B30 Wesley Chun Silicon Valley, CA 200898 --r I:! DjangoE*SAdrian Holovaty$USimon Willison~iE~%$I~~~%&-ZZEfK# World Online%Z&o 3W2%g%E@3&%%~%@BgE3&%N%%o &WebQ@3!iZtl8 T $ZKl%A%, Django@2005%7h IT%-+%&% El /L\\f %$, E %&%, &@24YHl%fB& h@%t+Python E%&k& &Web@% T , DjangoZ%3&%"IBT kEir;ibi!i%, $*, DjangoE%$flRgPython&%g&$fi%*T, %2%Z&%%Web@% !i!$D tL&S$%& %fi, Worid Online5$EkEf&JaDjango, %&-5@1L\F%96Z&3P3!1fTo @% $M Django?@H%@U%, &%E&&~$U%Q~@E%~~QFB$ETZ%~~~J\~J\&?@W gT. S!!! %-Bj$%%&YlJ%: The Washington Post The Lawrence Journal-World Google * EveryBlock Newsvine Curse Gaming Tabblo Pownce &@293%&TkEKlDjangom%?f:%?ll~, @2DjangoKllH$jT;a&-k E%%$FIH, %%% %'fl'l%P6$&$g+k-o Ls .................................... ';dbUf$j4 or/ ..................... WX ~lcl.al!dxT Ei 3kj S'L . $$ 6'2 5s ..................... 921 ........................... ~1a!da8~~urXll@ P'L ed$$fV&g8018?3 8'Z 2s .................................... 821 ....................................... '11d83 E'L U!L=PEHR L'Z 1s.. ...................... L Z[ .............................. 89, ................................... 921 .......................................... iz%$ I'L $4 W %ff E%Djanso)b7ttjF.R%tk $$ll$ $&Django$@ ........................ 189 11.1 QgX~dmi .............................. 189 11.2 {jkjHB+ .................................... 193 11.3 &&T;&*# .............................. 195 11.4 a] fj %XManager%%$F!Django ORM ....................................... 200 11.5 FA&&;Fk3 .............................. , - 202 11.6 o@ .......................................... rlrr.0 211 12$ 8&Django$p 8 ........................ 212 12.1 g51a~$ .............................. , \ 212 12.2 $ ZXDjango codebase ............... 214 12.3 @;k: .......................................... 215 12.4 #lxDjangoEH ........................ 223 12.5 ,is@ .......................................... .,-a 229 Pit 3 ~ffj$~ ++fig& ................................. 231 uf 2B 2 $sfiDjango ........................... 240 Ifgc $mDjangoff.gxA .................. 254 NfSD 2% . i?# . QAIDjangoEH ;f;; @ .......................................... 261 uf%E &Google App Engine+@N ~j~~~~ ....................................... 264 # 2F & $ Djang0$ ........................... 273 3 ...................................................... 275 (003 ',06ueCa,) % ,pg laqunu axe sq pup uoq2l(d, 2uyxd :I == ooj pue 7ndrlno-~oqs 3: anrJ = ~nd7no-~oqs "$$=>> '=vW '~F~!~-L!~L!!3G~??Xl '(<>) T!%$YY U (-1 x '(1 I Z '1 5 '~d 'El% 0'0 (lo~e~ado//)uorsrhrp~oo~3# O.Z//O.I<<< 0 (loqexado //) uorsr~rp xoo~j # z // I <<< 5'0 (spuelado.~eoT~) UOT~TAT~ an12 # O'Z / 0'1 >> 'Python and' + 'Django are cooll' 'Python andDjango are cool! ' >>> 'Python and' + ' + 'Django are cool!' 'Python and Django are cool!' >>> '-' 40 I__________________----------------------l >>> 'an' in 'Django' True >>> 'xyz' not in 'Django' True ~~~#~%~ &ii1&ai.5:ak&&~I]~@m + *figFj, %i.5:ZW%#w+.rs;, %&;ik%% 98 $$a+&-&, @W&.)P#k~&q%&. (hi;fk$l$ El$~&#PythonTC%%3%#&, &%W$+fi$ lq %-i$,Y%4q4%&irl$k+T ? o) $14~+9$$$iiii, i$T~:Xmt~k~G$-i;+%i+ie~9fi$18&.I.I:CfiG (96) $i&.lX,'foo'+'bar', 4g&$+'%s%s1 % ('foo', 'bar'), ;5 -4 fi & fl join3 & , $+#I] W %%&- $ .);4&-&t5$ ~&$ '$?3IW, $4 4v".join(['foo', 'bar']), ~t-f YlJ &$iiit, extend3 & d T vX&;5 --+YlJ $.+ fi ($9 bLlistl += list2, list1 .extend(list2)%M ), >>>book=['Pythonl, 'Development',8] #l),$~@g~s >>> book.append(2008) # 2, ~ffiUH% >>> book.insert(1, 'Web') # 3) %AH% >>> book ['Python1, 'Web', 'Development', 8, 20081 >>> book[:3] # 4) @ft-%~?~% ['Python', 'Web', 'Development'] >>> 'Django' in book # 5) jr;f%I$WhQ? False >>> book.remove(8) # 6) ~&%b%~~%. >>> book.pop(-1) # 7) &d%$l$24%3$% 2008 >>> book [I Python', 'Web1, 'Development' I >>> book * 2 # 8) %%/@%q [,qaM, ',uoq2Ldl ',xxaudoxanaa, '8002 '81 yooq <<< i $!JflaF.kk$l '-....$f#$g3%X :gS # () 2xos.yooq c<< [800z '8 ' ,2uaudopnaa, ' ,qaM, ' ,uoqqLd,] = yooq c<< O&%x%#?@%$ '$#&$g%#$f '~~14~tb&1@!4!@$IE%L!~% +?$b%I14 o~$%~i-%#~%?@~.!%!4!i 0%#M!&!g%dk&k-%Z114 ' %!6d%fl$ 0334$2Zl-dZ[~4+-%H '6 OSkliM * ~&j%11$%!5% -8 0 \ @L+- (El%*) %I@ (?$ifla) S~@%~L "3%@+ZTr4W '~gMZ?31.1y '9 " (%114&Ef9%SzU ?$%BY .s "Xm&-M$U&E%@% O ( rK%i) $Bt~-Y%TBTl+I%3 'E "@;j$;+-t$~y%%%ZI143 '2 o14Y-*t+&-Tl r :&bdYYTi-%%%%%LJ!% [ 06u"Fa ' I q2m1 I, ?uaadoranaa, , qaM, , uoqr)& ,] yooq <<< PD4&'%Ci3#9 (6 # ( [ ,o6u~Fa, ' ,rlqrn, ] ) puaqxaa yooq <<< [ I rluawdo~aaaa, ' I qa~ I ' uoqq&, ' , r)uawdolaaaa , ' , qaM, ' , uoqr)& ] 6urr2sXm 7u~rd ccc ,japosyun sy srq&,n = 6uyr7sAm ccc rrl rq 7urxd <<< ,araq2u\rq, ry <<< I , , axaq3 ?'I!,, = rrl<<< I r lawnu ST o6ue fa, I9:1s) % ,P% lawnu ST sa, <<< I.! u \%L-X ti $1 $3 Django Python$ S 15 import time # use time.ctime0 for timestamp VERSION = 1.2 # set application version number def sendXML(data) : # define some sendXML 0 function IsendXMLO - transmit XML data' # [...I payload = super top-secret information' sendXML (xml % (VERSION, payload, time .ctime ) ) $1 P Django Python& J4 17 str list tuple len max range sorted sum any. zipo (s;llTEP&) PRt;T$137I; (BRrepr, unicode) ?U5%7I; ng3z H%m% FF?II+ "&k&" H% (%Rmin) i$Z$,@,gT;lsRfi&$ (BRenumerate, xrange) %aflkfi%b9?lJb (8Rreversed) B?dE8n%a (BSrP) , Z$BfiZ$&True? (BRall) %ElN+EBb9%Rb, #+@+ZB~$TN+GS~l~Hfib9ZX %i.%Lik% &&Y&&$%k "&Pl]", @&RP%_t&O&&~r'lRl&Prr$ "Ti&({" I+P_t, &Lijt6$"r $4{#P&4$@4T%4g&Yll~&&tk&, X%$GTr'A&(X.$Lfi, .%40&911, &{X.%, &A%. T&~@'&$PL ffX~fiF, O&XY%&T&ik&Y, $.6,# o. zip&&&$% +&PI, !kk$$++&P~l1.f8fiiY R%$a&&--&9mk -+m7ita, ~kimmm7i~ata~ir5Y1J~~ ~ir5~ffnrtl+&&~l1+g+i~-ttd;kz~ ++~+Y#]IT: >>> zip (11, 2, 31, ('a', 'b', 'c')) [(I, 'a'), (2f 'b')f (3, 'c')l P&~Pyth0n!Fi~-~s4tHW~~ P&%T$KJ, %&8tl, k/J\q?St9@lg&H, %WE &%%&?U% (hashes) &2%l%%g0 BYW.2&~&$l~~B#U!U, !!lfi%%M#!fi$ET$%% iAl'dZSffi, fiH.P&ME#&? (0) fiT%%%? (?US) %E/1\+6-3 (ZB) %ZXFJ~ P&% i3 K%P48tlPythonES!FiBf %~&%8& Wkk$%PythonN&mSGQFo T~N%SitA%2%5AEN&, ~&A$%t~aTa~G~~%--+?&aFB~emEIBo EIigbiR, &lrl%%%%S#AEP&LLR%;kTitA *%W2*, 5&$~&4+&& TEE-5$n!~l$MP&HfiU30 &lil%i+ik-T%~RWHl+MUR~~~%%@!TR. 3&+u~%HMi&, >>> book = ( 'title1 : 'Python Web Development1, 'yeara : 2008 ] >>> book ('year1 : 2008, 'title1 : 'Python Web Developmentb) >>> 'year' in book True >>> 'pub' in book False >>> book.get ('pub', 'N/AO # where book['publ] would get an error 'N/A' >>> bookl'pub'] = 'Addison Wesley' >>> book.get('pubt, 'N/Ar) # no error for book['pub'] now 'Addison Wesley' >>> for key in book: { ,o6ueCa qrlrn rlua~do~aaaa qa~ uoqrlha, : , awrl, '8ooz : ,lead, } p <<< ,o6ueta qrlrn rluamdo~aaaa ~JM uoqrllh, = [, aTrly2, ] p <<< [IF~IIQ TJQ <<< 'Y%M%&.YZD$El%&T' '#Y!-@%@%*%%ia~HbjU$g@%L)}% ai 0gl+-&E%33 '%M%~%MP~%2+-HB#+-%a$j%~$~Yd '%!$$#% $8Zuorljdd2 "~$SM%%3HVl+-C$~rC%B~Tr4EB@MP9%2+-HMK$1~%~ Lg%gb?N+R (uo!~!1103 da~) u%+@,, #%-$!7IlE 'gMg[14#~%7$&$1%1$ ( ,rluawdo~aaaa qaM uoq2hd1 : ,aTrlyrl, ' ,da~sa~ uosyppv, : ,qnd, '800~ : ,reah, ) p <<< ,haTSa~ UOS?QQVI (,haTsaM uosrppv, ' ,qnd,) rl1neJaprlas.Q <<< ( BOOZ :,xeah, ',3uawdo~aaaa qaM uoq~Ad, :,a~3y3, } = p <<< "%l%%d% 9gum 'H Lc[da71j3!~n F- u(~a7)ja2.13!~,, H~~Y~WR L#a-~~~gg EI BYIW 3 'M9%%T '%-jaa@H$!M'$ "JI~~J~P~~~~%RIYMY%UY~+-% "%1%%%3*Ygl+-El R%B3&E ' +3uY3%q1az%L TlH* o%l%+-EIR~[lq~d~l~~& 'gv+-M%*%*lqndl%Il$gMER "~I~~~IIP '*-€i3 %4-24r%Eh4$W%'% '%%&?+RIYHTlk'Tt% ' (~uONE~F~%%M%Y~%+-%RZ%! $gJ%%n$) %g+z%El%3 '%M%*&P9k%Mjag%%BJ%flV '$17%66El o%3W%4k31HM~~~~+3Pw*~$%~R%TT& ' ( i l4$H3E L.V% '%M$~~II~~~%L/\%%I$) M$%%BM%* :Y%M~~W~~hNLll%YINY~kZ% 4% 03Z%%J-LHL.IJ.% O@r;tlZH--?4%Ekk%%LIj% O%-##-%gE#%*+3ir;tl% .L "g!La%W@~%RE* %RIY~a~Ha%id .9 "#5!-@M%+-\fflY 'S " (%T%%Ma$%RP) %MB%%a%%YjagHa .I7 "(aK%- 'Wm- '%H) %+%~%%!HMW*~% .€ OB#+F!%2 .z O *&*%@%Midl3 "%%+-@*&*4-9%Q3 '%*%@+-Bhg .I :L-%8%L#% i7+J%L8l@Br;tlMYT7IlE 3uamdo~aaaa qaM uoqqhd : a~3j3 ha~sa~ uosyppv : qnd gooz : zeah ... [hay] yooq : , 'hay quyxd . . . alepdn dod 1aS sural! sa'nle~ sday PT'E Z T EZT 0 a ',,e2ep pyIeAuy apy~old noX :80883,, 2uyld :a 'uoy2dasx3 ~dasxa a ',,pannsso lona q2ew amos :80888,, wyld :a '.10~.13sy2amq2r~y 2dasxa ' L&kEZ@u+-s6&L.II.3;aFz'n'-G%%g+gB%flk@3B%8-H (a)qs 'asTed uln?al :a '.IO.X.I~OI 2dasxa ( ,I, ' ameua~yj) uado = j : Xz2 lorra uo um2ar 'a~g uado 02 2dua22e # 08&bgX%%2$k9d)4BF~10~11hd k&3$!l:l$k!i$$%L %[149'1g axaq 6uyssasold yeuxou # (,,ixa6arruy ue ur ssed Jsnw : 0003 ~ou~,,).Io~.I~~&(J asrex : (2u~ 'quy-a~~~~soKaq-~snu) asueasuysj rrou jr xabarrur 3: ysaqs # ,,,,,, rrr ssaso~d pue xa6arrur aa~~~sod aye2 -- 0003 ,,,,,, : (rrur-anrrrrsobaq-rrsnm)ooj jap "@M&&~;-S~YXMB~~MPII~-P (?'$+@+#+ -~#x@wZSs~~r~%'~~) Y pl ~%#POP~IIHZ%~~T~~!~%#-F~?~#F "FRQ ,,punod ION,, POP d~~~%-'f-%oSu~ra~$@8&%@~0P~ll~~- '4$ 114 " @ tt!-#??Y ;8tflyoSu~fa~$j$$Y+$#$&Y3 "@%@oSue[a[fl%& II -I-%% 'Xf%&k?% @$x~x#q $YR'Y "&% L [fl-@sY?osuvCa '$+-$z$uov~~dbQX~~H.d$ I.! u \v*--3 x' %I $2 Django Python 8 25 reap = h.getresponse() print IHTTP Response:' print status =', resp.status print reason =', resp.reason print 'HTTP Headers:' for hdr in resp.getheaders0: print I %s: %sl % hdr >>> check-web-server ( awww.python.org', 80, I/ I) HTTP Response: status = 200 reason = OK HTTP Headers: content-length: 16793 accept-ranges: bytes server: Apachef2.2.3 (Debian) DAV/2 SVNf1. 4.2 mod-sslf2.2.3 OpenSSLfO. 9. 8c last-modified: Sun, 27 Apr 2008 00:28:02 GMT etag: 116008a-4199-df35c880n date: Sun, 27 Apr 2008 08:51:34 GMT content-type: text/html >>> check-web-server (port=80, path= ' / I, host= 'www.python.orgt ) def check-web-server (host, port=80, path= '/ ' ) : 233, +Z%U%@?B!!&%~EE~~ %@?B&R834? " EI!!&iAH", fi%iAS&!N% m~ %6~~fit~~m~%-a~~~~~~qq~g~~~, +~:i~~-mz I~ln~ def check-web-server(host, port=80, path): # INVALID >>> def func (arg= [I ) : . . . arg . append (1 . . . print arg . . . >>> func() Ill >>> func0 [I, 11 >>> func0 [I, 1, 11 GBEFirst-ClassX$@. &PythonE!8FfLA%E3& ($!I$&) ~!T$P$M~&-#@J@M, !?J$u, Ek!IIGl&&B %!I!, ~~&%~~~~, !lv$s%i%$%a&%o %-@J~R~$%F~U~+I.~&~&, $k%E 3 Ntk+i39$PB&M7 $%$k%&%!T 7-'? 13&%8f%~ &%Ai+ik2%, %!I'I%Z@R%& 31MmHko $1 m 3%$?defZQ~Mi!%, !$%R~%&~IJB-?@&H&%%%@!~%%%%U 33&*ehl 32EO--+%$k, !!!3qUR2ei+$3IR ($B%alias) 2i%%-+o 6&3$%6l%--+E3 &iRR!%iZ--+@4&8&, %EBA-+@#, $E@!&%-+E39EH, !$8%313+%& 6~1B7-+~$9\i%GlM, %%i&$U-&o IT%-+!?I%, Tfi@JR@&&E%$2rd!I!filJB7$2-+, fi2E+%E3 !A%@& --%ZX, kGk+~Z!&%Et2iI-kEF$7 : >>> ~OO = 42 >>> def bar(): . . . print "bar" ... +pg(&python3#&-#, @&~CJ~~&23~~~ffl Tfi3-!Ji?ll+%i&22G839M0 fi$~~barF]iE$$M~&: () uoyl)aun3 . . . :2sy~-uoy2aun~ ur uor2aun3 103 <<< [Zeq 'xeq] = rlsy~-uo~-~aun~ <<< : " L Ydk%%g\/%€r #&!?4\/fT@%% '3HISk#-%#~J%U$%X# '%#%@MS#@3JW&-H%Z Ozeq c<< =eq Oxeq <<< ~eq = zeq <<< I.! Y - 8Z yer)oJ uzn3a.z (ales-qsea) rleolj =+ TeaoJ : saps-II~ ur ales-qsea roj 0-0 = TnaoJ : (saps-TIP,) le~o~-sales-A~rep jap (s6.1eqoq++) laqTr3. sqsaCqo.r(~oq~ = sayloqs-qoq ( ( I auTThqI ' I qxa2, ' , anT2qns, ' , anyq, ) uy ; 103 ( , qoq, ' , su~~2uos-, + 3) ) ~syp = s6leqoq (s6~eqoq++)~a~~y~~sq~a~qo.I[1oqs = sarloqs-qoq ( , qoq, : , suyequos-augdq, ,qoq, : , suy~quoCqxarr, I ,qoq, : , suy-equos-a~2yqqns , ' , qoq, : , suyequos-a~qyrr , ) = s6leqoq def log(func) : def wrappedFunc ( ) : print "** %SO calledu % func.-name- return f unc ( ) return wrappedFunc @log def £000: print "inside fooOV >>> £000 £000 called inside £00 0 @usergasses-test (lambda u: u. is~allowed~to~vote) &ZX+@1+2, %l%kZ%lH 7-+@B, %G%D-?@gki%!E'&%-user- passes-test$ Z#$Z-?%%%, %R+xB-+#gTg&@@#k, ~~J+J&g~&~H -+iq~~~gfj~e &pJig&SS#pJ: edecomaker (deco-args) def £000: pass £00 = decomaker (deco-args) (foo) @decol (deco-args @deco2 def £000: pass £00 = decol (deco-args) (deco2 (£00) I&&iT2E, "3114 AZM%th%nP," ? gkk, &B@&m&&&PytllonLli+%!+A$fi m%fi, H#@%~%, $gzk#~%~!~i&R%m~~&TS%m&&o +nm2%ttii%~u ikf%R-+~@m@R~~&~-in3!+o ~n%f$~~-#~z@~~~~%th%@@, EijjMKent Johnm "Python Decorators" & auoqd = auoqdbjras aueu = aueu.jIas : (auoqd 'aweu '31as)-qpy- jap john = AddressBookEntry( John Doe1 , '408-555-12121) jane = AddressBookEntry( 'Jane Doeq, '650-555-1212 1) Python2%G?%~J~M-injt-, i%%ZHi2?-%&o !?%I%, @li#t$~~@RH%% self, E&narne$Uphone number, Python&%$$!f Aselfm,, R&$$$kqU&@iij)..7B~k 7 , t-k4~john.name, john.phone, jane.name$Ujane.phone, RT@m@/!F, &$k%%DJB1BmiArdt9&!thB%~: >>> john = AddressBookEntry(lJohnl, '408-555-1212') >>> john.phone '408-555-1212' >>> john.updateghone('510-555-1212') >>> john.phone '510-555-1212' class EmployeeAddressBookEntry(AddressBookEntry) : def -init-(self, name, phone, id, social): AddressBookEntry.-init-(self, name, phone) self.empid = id self.ssn = social ()dnox6.m 2urnd :auoN qou sr m 3: <<< (,poojeas, ',oo3,x)q3qem.ax = m <<< ax ~xodmr <<< I) I~TP'E~~ eud se 601e~~a.[lqo~~auoqd qrodul !S%PythonZfiElRf%mZS, ~B~Q$UI~%O~PZ$~-+EXIJ~&BTQ~%~B&& $9ZiE1%$9&;%r. Python%tG%new%%TQ%fi$#t%g&m%@1J1-i:fi$m% ., $WE, Python$ , %fi$.611&%@il#iWHB4fi1~@B-3%Bfi$~H%@.6I]Zi~%2G, @ZBPython%%ili E! ifif$2GmH$9g-+3&0 em&$z-init-o %%@l1td+%, &%R%.61J&-+H%l fi$qU@iNH EI%-#~WH~+%~ \ >>> class MyClass (object) : . . . paas ... >>> m = Myclass0 k8b, &TPython&%fi$ $ i&mH-init-, $u%Q%%@%$!f%, fi$&5BB "$ZJHn %i%l Nf%B!?k%eo >>> from time import ctime >>> class MyClass (object) : . . . def -init-(self, date) : . . . print "instance created at:", date . . . >>> m = MyClass(ctime0) instance created at: Wed Aug 1 00:59:14 2007 >>> class AddressBook(object): . . . def -init-(self, name, phone) : . . . self.name = name . . . self.phone = phone . . . >>> john = AddressBook('John Doe', '415-555-1212') >>> jane = AddressBook('Jane Doe', '408-555-1212') >>> print john.name John Doe >>> john.tattoo = 'Mom' >>> print john.tattoo Mom # ! /usr/bin/env python llH1tfoo.py -- sample module demonstrating documentation strings""" class Foo(object) : ltlltlFoo() - empty class . . . to be developed""" def bar (x) : llnltbar(x) - function docstring for bar, prints out its arg 'x'""" print x ZsLE%!% "~UEiZi7WiiiFI" &3OZ: 4n%fiE3#%%#%A@&W, fi~lUiBa6i /I't%k, %$~@&$lrBt-doc-R1EP%ikl'.7 'G&docstring, >>> import £00 >>> £00.-doc- 'foo.py -- sample module demonstrating documentation strings9 >>> foo.Foo.-doc- 'Foe() - empty class ... to be developedt >>> £oo.bar.-doc- 'bar(x) - function docstring for bar, prints out its arg "x"' >>> help(foo) Help on module £00: NAME £00 - foo.py -- sample module demonstrating documentation strings FILE c: \pythonZS\lib\site-packages\foo .py CLASSES - builtin-.object Foo class Foo (-builtin-. object) I FooO - empty class . . . to be developed I I Data descriptors defined here: I ( -diet- ! dictionary for instance variables (if defined) I I -weakref- 1 list of weak references to the object (if defined) FUNCTIONS bar (x) bar(x) - function docstring for bar, prints out its arg "xu dd-s~m 1~:81 gz unr LZZ xqd xqd 1 --I--I-MX- ddesbu.rqqas 15:81 92 unr SZ6Z xqd xqd 1 --I--I-MX- dd'ab~u~m 1~:81 gz unr gvs xqd xqd 1 x-zx-IW- dd.-q.ru.r- 1s: 81 gz unr. 0 xqd xqd 1 --I--I-MJ- vz TP?07 T- ST $ aq?sAu p~3 $ ilXM 01 1ig 'qW &I punl~m> 1.uJnw mA p.,e aly IbUiual Welo .r4 18 ocl. - mew *R( ,d arnr,aq UIlrlavl r!q, waar a8.m~ ,Tlarud.de.; Wmaa M.P~*LRIIIWIP~~~DI~ ~o~lldL:uun~~q bd~)~ly IMIIJP~ . Ks.tsrrwn*ias;a;eMi~ u! rSuplas .-=FIEI~YO *ii,pa 'arrqnpp u arn 01 veld nda . dd.sna?a EE:OZ 91 unr gz xqd xqd 1 --r--I-M- dd-s~apour EE:OZ 91 unr LS xqd xqd .[ --I--1-M- Xd--q~u~- EE:OZ 92 unr 0 xqd xqd 1 --.I--I-M- 91 Teqol Ifj0I9 I- ST S " ddr! 301q&~$$EV~Ada31!~1!w E~~%&N.I% "L (,,dd~, %?i%~o~u@a%) ~~BC~Y~ZWKI 'XI U~L& from django.db import models # Create your models here. fij%&R, fi~h7;?1JRG: class BlogPost (models .Model ) : title = models.CharField(max_length=150) body = models. TextField( 1 timestamp = models .DateTimeField( ) 32-+%%Hmodel, f't?&T-+&3?5@3!23 uBlogPost" 3$&, (Pt&%%Ei364+, Django$~&X@~model$ afiRL--+ $ @!!$I, Uf&-midgE. ) ~~~~~BlogPost~~django.db.models.Mode1-, 2EDjangojhB@modelI#k &H%l#&%, G%Django3Zk~3$%%%&% (ORM) %%!23@~L, k9b, @--+$~%B%R ~%m%~l~-$$#%X%-+~$Z$E% (field class) H%DJo iZ5$B%&sE django.db.models~~,!X, elili%l$$%, MBooleanFieldElJXMLField~~~&, qiJ;l;k% 9z%2!lmlxlxz?o ~R~A~~~&HP~~~~~~SQL&M~SQLS#~%%&B&$PD~~~~~B~.Q~$H. %%%6'?$i$k l%@P (3l%1$F;r$k/a\3!iwj/1'$$i@T): DATABASE-ENGINE, DATABASE-NAME, DATABASE-HOST, DATABASE-PORT, DATABASE-USER$aDATABASE-PASSWORD, DATABASE-ENGINE = "mysql" DATABASE-NAME = "d j angodb" DATABASE-HOST = "localhost" DATABASE-USER = "paul" DATABASE-PASSWORD = "pony" # secret1 SQLite4Ef#Z~$i!l!Ii$, &EqU%I@?9%kB%E-%AMT38T0 H%SQLite4%A$i& Zl~%%1~%GMfii-%HAE&~ZI4-%$%;f;L$PB%l&t3~~@4;-r], @$fin, % U .' A P$%f4 2,- EEI1kDjango/a\Z%ZDT&fi+iffE$k2E@N$%MSQLiteB%@ To DATABASE-ENGINE = "sqlite3 " DATABASE-NAME = " /var /db/d j ango. db" bATABASE-ENGINE = ' sqlite3 ' DATABASE-NAME = r 'C: \py\django\db\d jango.dbl R&b%~U&%~jangoHfS~21R!&S~1~,$,,&S%&%&if:Hi5t~ER@@%%!&%~ I$ +fRiR$: ./manage .py syncdb # or " .\manage.py syncdb" on win32 &Djangoift:E&%&!&2@+f%%%FdWlU&$$&%& : Creating table auth-message Creating table auth-group Creating table auth-user Creating table authqermission Creating table django-content-type Creating table django-session Creating table django-site Creating table blog-blogpost You just installed Django's auth system, which means you.don't have any superusers defined. would you like to create one now? (yes/no): yes Username (Leave blank to use 'pbx'): E-mail address: pb@e-scribe. com Password : Password (again) : Superuser created successfully. Installing index for auth.Message model Installing index for auth.Permission model Loading 'initial-data' fixtures ... No fixtures found. I((, s~m.uplrpe.q~rquoo.o6ue~p, )apnlou~ ' , /u~upe, ,I) # :uyupe roj syqq quaunuooun # "s~_I;Y#zM+hdd~1JnMY%@ @3L R&~3%2BY$4 '3k~~1%$#~~8n+-$~+agZ8L~~% 'gflddvgSg81 'punoj sarnqxrj ON. - . .saznqxrj , eqep-lerqru~, 6u~peo~ lapour hrqu~bo~~urupe roj xapur bu~lleqsu~ 60T-u~upfibueCp alqeq 6uyqear3 qpouhs hdsa6eueu/. $ Select blog post to change j "IogPnSl rlllert [ 21,gms ! IU~~XSJ meir'1~35w+m Bzf $j&%TadminI&, BPlfjladmin app@#%4ilWmodel0 R&R~#$9b~fi4'if't~UR~ - lI& E~$!Wmysite/blog/models. PY *#, &fi~-$-BlogPostAdmin%, ##Qfi1EU&#f't@3P-1'ig., ff%R&madeIs.pyB& *ES$+& : from d janqo .db import models from d jango .contrib import admin class BloqPost (models.Mode1) : title = models .CharField(max-length=150 ) body = models.TextField() timestamp = models.DateTimeField() class BloqPostAdmin(admin.Mode1Admin): list-display = ( 'title', 'timestamp' ) o%#lsod201a~Y5(%%%%li$% '-frb$$k!!%-@ (8*% ugg~ggfS?ij&! 'GPWi%%#) ]/vtloH$~Z'riL-k-F 0B~@3@;SI-~6%%%%#04u~!a $)?@y$L!jg '&%&1~-~1~~o]/v'l~~o~'9~'o~u~~~~k$)~lsod~ol~;dfL!~%k~ ' L)93 oaIg++ma~gY~%g~i L~~sitlg;4g3u037an~~n~ 93 "~~+-~~~~~~~&l~~nb~~dll~'dll~~o~~~~~~~~~~ H@08ue!a+B$ :L)rjg "%@ EdX+$Ei-%!#kh%%L!j% '(%a$@BMZ%L!j%LY%Llj3) -L)VIIfllodm!E%% ( (3)~apua~aq) asuodsaxdqq~ uznqax ( { sqsod : , sqsod, } )qxaquo3 = a ( ,,Iuqq.aarq>xe,, )aqe~dua NX -3+ m+ ttz h 3 0 a CD - 3 Hm $In 3 2 3 I m PI- dm 2 4. * 2Y $6 5% 3 L- 9 s $3 8i 9 3 Et B a 9 3 M -H 3 44 3 Mm e 0 Ei 33 w ia dm PI- S s W Yr@ 3 $ % 3 9 ern m a %? = LI= M K- 4 BP >-$s 9 rn 3 ta 31 w Pi= a FZi 32 IID w )--7 r= LW. Im E -J '8 9 %J' 3 3 I3 PI- % s 4 % N * Is' -U. * 2 s PI- s Po - I Fig 3mx a? s35 - Fl@ P. 8 e, a rng UQ 0 z%a >+ +& +& 3L 31 p$ I + G & 5 II " - 2 V Si EB gi w rn 3% M isi )<- 3 4 am !4f4 9 =r 31 % s 3 H IlE m B 3 a =? - !s' a B 3 a - him a P s & -+C~ntainer~r;luZ~--qparent~~~ft&~$-+Container) $$%(lJihg (tk$REmployee ~r;ll2~~%(~supervisor&~hired_b) m!-bf(@1WgR0 %%ForeignKeyRZXT%%H-%, $1'3%-%i!P%@#3%%2i@JH%~ 9~@AIA*k NE-+ "%H-" I%%%, RPTUG%+3H&31fflR-+X3$&o Eik3H&RG--+X H$&?93lR, ffijXH2t;Pi3&i3blEIJ-iR3H&0 $kEib9@!3%R, $$r;lUZ#EMBook$u AuthormgfiiJ: I # Pull a book off the shelf - see below in this chapter for details on querying book = Book.objects.get(title="Moby Dick') # Get the book's author - very simple author = Book.author # Get a set of the books the author has been credited on books = author.book-set.all0 - 2- , I-*, BJltrtl@&@13-fnT;: class Author(models.Model): name = models .CharField(max-length=100) class Book(models.Model): title = models.CharField(max-length=100) authors = models .ManyToManyField (Author) # Pull a book off the shelf book = Book.objects.get (title='Python Web Development Djangon) # Get the books' authors authors = Book.author-set.all,() # Get all the books the third author has worked on books = authors[2].book-set.all() ~an~~o~anyField@l$B@gT&a"a"6eI]& T-%%m%%h&a$%%%&?&%f %, fi S%2?fB!%!I12SQL~9b@, %7%, &FlW@&7RG &9b@k0 ii%P+%%bDjango ORM!%@HSE+-&%%,%@%m, 5qU$&&iQ&, J?%% - $2, I$qU$ManyToManyFieldk%Z-+%%@l&q, through, %~~~I-+E$!YJ+ ifl&2%o B2throughf$Tl2+3%FEii?+ id%k&$G9l\ ,* XZ, EL mW38t%%%@~FB%%mEG0 T;Ei!%K~$~2iS;iManyToManyField%fiU-&-#, i%T k$i$-+E&l%+ ifl% Authoring, ~$Ej;%k&jj'~T-?collaboration-type~E, %&i$thro~gh%@k$tgRS%%~ class Author(models.Model): name = models.CharField(max-length=100) class Book(models.Model) : title = models.CharField(max~length=100) authors = models.ManyToManjrField(huthor, through="Authoring") class Authoring(models.Mode1): collaboration-type = models.CharField(max~length=l00~ book = models.ForeignKey(Book1 author = models.ForeignKey(Author) \ ,sAessa,=adrl~-uo~~eroqe~~03~6~~10q~ne ',unq3,=q2~spua-aureu-roqqne )ra2~r~.s23afqo.yooa = suo~2e~~duo3-hessa-unq3 unq3 6u;a~oau~ syooq uo?r)e~yduro:, Aessa 2a3 # aIlTl'jTas uxnaax : (j-[as)-apo3~un- jap class SmithBook(models.Model) : title = models .CharField imdx_length=100) genre = models .CharField(max-length=100) nuwages = models. IntegerField() authors = models .ManyToManyField(Author, limit-choices-to={ 'name-endswith' : 'Smith' 1) def -unicode-(self): return self. title fl%Z-47%ZE!$$U7Sfi&%lfUESmithBook%@JmEf$, %UT&m&$Jb%Z& &&yJ: smi th-fiction-books = SmithBook.objects. filter (genre='Fictionl ) $ZR%%!ilmZ?DJ3$%iBSeR$Q%&a%g, BR@~E&%%~U&BBBOO~ % %%-ill, K2%n%tiii6$J3m3Ir#, 34332 $#ZJ!@xEk@~DRY~ktf 7;fi%i.$I]m$%%$jTi (multi-table inheritance) Uljzze %!~li%+#*zmih%o %?Q%&Eb%%%%&mE: $3%!N&B%Meta%%jTi, &%%!JX%%!~eta%&# @% ( 3%%7%&abstract%%Si5%False, %9bZG--~%~&@Ej(;Ei%%42, bl;k~db- name%). k9b, fm%gWN $1 Trelated-name&&%~BFore~gnKeyi%#~%%~~~%, $%%% N-!k%B%3$ $%I$M#Ufm "related-employees" 2 %i%?#EPfl$ , fiE~N%(class)s, tt;fras# "related-%(class)s", (~~j$$$~fl$~~~ &l?iSS%%l$) s#, 3%m&P$kitZa@&, B%E&#g0 8 A%% MzXk%&, gSg7f;i (multi-table inheritance) $!J)$&&Eb%~~XIl$kO ZE2R EuPylhonm%i#7$k, @s;l;R%%abstract = TrueZqMeta%j&$T. &#$~&$%@J$&~$J ~BkfiG, $%S%&$n%!ilKG%Fr]m&%P-t+, 3%%MX%%7kFh6B1/4$uk& (R7Meta %%!!%-%#fl9b EKi~l~ll~~JM%ZT 1 - ~~&%!%~%~~&~h%~!%#JL%~o &SEE!, X%s#Ij6 !!j E!,&iE%!%%%~jang0&$3, WJ LAZ$&%i?U!k, Flkji3$8F! @ E!,!%E1k% ''!E%'' 3?ko %%, s%&s @ 3&3%$~X%2 idisi-qOneToOneField , LJR&%m-%/J\FEffefi+3rf&S&-@$%Rm, A-~~~~Rx~~E~I+~ class Author (models .Model) : name = models. CharField (max_length=lOO) class Book (models .Model ) : title = models.CharField{max-length=100) genre = rnodels.CharField(max_length=lOO) numqages = models. IntegerField ( ) authors = models.ManyToManyField(Author) def -unicode-(self) : return self.title class SmithBook(Bo0k): authors = models.ManyToManyField(Author, limit-choices-to={ ' name-endswith ' : ' Smith ' 1) %fi@$fl3, 2EjZ%-m+H%%?$fiMetagmabstra~t%$~ j!E-qe&%@%Ui$+ models.py*f+k~j~manage.py syncdb&+gfilj&t+&i$m% (e$IJ%Author, Book8U SrnithBook) , fia&&Hj%)l!&&H %#ij1fi?&Autho~mithBook0 &~SmithBook~@J~~$~@Ibook~ptr~~~~~~~l$~~~~l~&~Book%@l, fiE? ($2- SG, $&Ta-.Z$E/L\5@+Q) SrnithBookstlBook~@@@$!l-+smithbook (t$fi-ptr%%) j?$'@. &Ti&%%&m%%fr,iTX%%G 0 ZE!%@!, ~etam%&$q%&&%%m%%q@rd a$@%o %CA, ~%%%ZE%$~SL%~~%J!M~~~%J~I, $!lli%?%%F$!29$73iiI (@Pi$ ordering$~get_latest_by?fi%&3%.%!X9 'ki(1&&@%&T%m) i$+i!2$i3DRYb3F!U$2t9 HE~BlJrBT-,fi, T3WB%k11~%3~ZT~!ifT , ~P%BFAB~-~~-%KJ~JSR~ SG, %4/1%~a-.Z%~%#~%7%1tA2?%&tkP236%!~1%bookR2, %kil'lqCJHbf %~~!~~B~Book~&I:AESmithBo0k1i,&~ 3~%l$%BJR2%&%%9i,&ii1&%B~m#% iQ~s;f-l%l&$[s&2%D&%&tkith&&~%B~Rt9B0 9We%%&i2mRflPpH (iE%WFP$[I 6f7) ~%B%g$g%?mo &2 (model) Fj!Z9A'.7$E (fields) $U%% (relationships) jEl$T&@&m%gI:JB# G&i@#~?Jj~~m FlhSgf ~-Z3~f$~~~f&~~-~1nicode~~~~get_absolut~ savedelete , 4, BPR%g-%uDjango%'Fi& /l'#gg%%f$Z&%lZ,Bm%X%Meta, 9, Met%&&8: tk$~&-/l'H%H .alaq yxom 2,usaop # Ieq? :pua aq? oq ,s, ppe 02 A~durs sy uor3ez:~emTd ?~ne~ap s,oBuefa # [ .aTppTu, ' , qsq, ' ,qsxr3, ] = laqqaboa-anblun 'p~xom Ieapy ue sy slqq # puaqazd Il,am qnq 'plno3 afi 'a3y~ -teal uy 'assno2 30 .aureu Tesyuapr # 8001 e q?rm uoslad e amq 7 ,ue3 am qeqq we3 aqq aposua afi axaH # [ , aTpprur, ' ,aslr3, ' , qsq, ] = Burlaplo 'Ae~dsyp # 30 alKqs 'A qslyd '~se? e Buyumsse 'a~doad laplo 03 Kefi ladold aq& # from myproject .myapp.models import Book from datetime import datetime from somewhere import some-£ unc tion-returning-a-queryset book-queryset = some-function-returning-a-queryset ( ) today = datetime.now() # -It turns into a less-than operator ( ~fi&liji&EfflEB!Zb!Jsql'F- H $T;#U.sqli&E, t~$~myproject/myapp/sql/triggers.sql. &{iJ S!:$~Zf$%Pg~!&5f31nanage.py$~SQL#H$%&.+4~reset$~yncdb, ~~~~~~~~l]sqlall& sql~.eset$&j~ !F.fi5HiG fi ij~+AfS, ~+++JR.Z&--+ $ Ei%rnanage.py&$, sqlcustom, e ($0 FUEEmBBEB U k%$'i $ZASQLZ@m, DjangomORM&S@H%B#gR%%nB%E2 Ml0 &%Django!&BEi%Bl%l$El, %B#3R&2K2%1t1 2B%ktil%bZR~Python DB- API&?#m, R~~~Adjango.db2~A~connection~~, fiG$kqU$XQl&Bj$&$&%1'ia i@7, from django. db import connection cursor = c~nne~tion.c~r~~rO cursor. execute ('SELECT first, last FROM myappqerson WHERE last= 'Doe ) doe-rows = cursor.fetchall0 for row in doerows: print "%s %ss" % (row(O1, row[ll) 2% $032 GF 9, ik&iXJPython DB-APIl#, ((Core Python Programming)) 9 G "&&&" --$ , &A#k.&%&i&@ 8343 ( !L withdjango.com) , 35$ URL, HTTP~$I~P&EI 95 from django.conf.urls.defau1ts import * urlpatterns = patterns('myproject.blog.views', url(r'^$', 'index'), url(r'^blog/', include('myproject.blog.urls'), 1 urlpatterns += patterns(", url (r'^guestbook/' , include( 'myproject .guestbook.urls' )) , urlpatterns += patterns ( ' ' , url(r'^catalog/', include('myproject.catalog.urls')), ) urlpatterns = patterns ( 'myproject.blog.views' , url (rl^new/$', 'newgost'), url (r '^topics/ (?P\w+l /new/$', 'newgost' 1, 1 urlpatterns += patterns('myproject.guestbook.views', url(r1^$', 'index'), url(r'^add/$', 'new-entry'), ) urlpatterns += patterns('myproject.catalog.views', url(rl^$', 'index'), ) ~+fi4+tkmim~*~K-,6,, ~Hzi$qUz2u3t-+R%~%+G3$8b&8&+ URL~Rl$~%R~~~&~~~$. XE?$+RJG?&G, &4~7$11i@%TBURLZX~Z~%jA "blog", "guestbook" $U "catalog". #+;f5lJ~R~&{(1~~+$GR K4k&gN$&k$&URL@~ ifi7-$- $ mFGR&!l!%%, !%T$blogERT@!IgE ((%!$lti;qLJ%r&.6d@-+base%$% ~umEM-2%Q~PE&!$~#~m 10 URLconf&$ (URL including) &rlj~3t(rf.$/i'&Hi~%G4~16~-@?~4~R$+j~R5% R* JU-+gm+u %%k B @&3% fl&2~11@ET~~~%k~%k4i3%i/a,~~R, ff%RURLconfQ$%",Rtf 7241'3. iR3AtIii/a,t&,6%&1$r#Z~, fFrjURLconf~k%l/~~~?&i%S~F~~~A5Z%, %=/&%- (includes) X& T?kk~kkZE, &i%--TLI2, &fiJt2%%SU 7URL%+5@3J$XH @%g&PythonB&@$3TUM$R$ %;fgZ, $i&A$%%-&z?&, DjangoZ&i+{fi{f A--'pV@Jm&%j& (callable object) , DJ4n : -.from django.conf .urls .defaults import * from myproject.myapp import views urlpatterns = patterns(", # Don't need the prefix anymore url (rIA$', views. index), url (r'^blog/', include( 'myproject.blog.urls')), 1 j&&-s, t.t;4niiTU{gm%R%@% (decorator function) $$I- &BH$XH (generic view), ZEflllBf$ $Z~~BFa%j&%E~&~Lf~~BC~~%i.JH. %llS~i~iGF~%T%R%URER~iAFa$XHW-%~~t350 - ~~~~~~ SE fiflf4&&URLconf3&from myproject.myapp.views import " &&%kN Tfifi&!46$ &fl&&A%fii%&n, ez&&;%te$ff.i'&ag&%sf&fi~t&8~hr'qa-t~+~~+ ZFl%&!,!Z&I+~ZX7 CIil i~ L%index&!!il. fiGAtL&4B~%Ik$~LZ~~k~lItl#~1-7- 8?#, i~&.i'&El&$&~A% C $ L%i!f$% (~B~0QSGA:XNfrom x import y as z&$fig&), i$j+&fi]T$AGj3+&%,g ~2i~T&ffj~a $5+ URL, HTTP$L$!I;~&JE~ 97 4ilWDjangof fi @Idict?&, QueryDict@I % fi], &+& ?$Wigit fi $t&l$&&&HTTP CGI def userlist(request): return paginated-userlistqage (page=request .GET[ 'page ' I ) S.S$ URL, HTTP&$$]$n&fl 99 Hk, i&e%i&A!*g%*xH a&mf2,e,7 * R&%l~l%%gfiB&HmnfilEo #%!(I* %, Al;ilE tki~~Zfi$--,&-Z~Z&%Qd%G&Sc~ntent~~~~~E* (body text), - E~~%-+E~~HTMLPR$, Gj+HttpResponsedk%S@, $$&fiJL?$EEG!374&,, %%Rm%&@~fiU&Al;ilEH&-Http~esponse@~-+$R${+%$g~@~~~&, g#$G#G$content9io response = HttpResponse("This is a tiny Web page!") response = HttpResponseO response .write ("" ) response.write("This is a tiny Web page!') response.write ("") S$k%B$$TUfiHttpResponseHSEf~%9-+%lU*!+#&~K64g (tkBncsv&&9i ~CSVKII~), &kZ%~&&KW&B%%%HPmlS,&, Afi~~&gI%J%--.S'%$$~%Ef HTTP%, S8if-$$qUEHttpResponse%f+s-+$fi %R, response = HttpResponse ( ) response["Content-Type" = "text/csv" response["Content-Lengthn] = 256 ~~~jangoER@~~~$%@5~LL%~$-~ (%%i&R, #%2U%&!%$!i!HEI&; &!El I u 8+2-F!2+idl4 (middleware) -3%PythonEI@qUg4.~3EZmg+~%;fk4'i%?P~P+fiH@$&~ A 2 $3~ (f@&iRB&11&m~1;iJE) ~jango%fJ+ ja714%1$F!2-+Python%, %%RT-?%Zm@ u , $k%B'i2?2XT- ~&~pr~ce~s~request~~process~view~~~~&~ (&TfiJLTZ, &{(]si+a&+g#$m m--5, ) &settings.pyjC#Z($jMIDDLEWARE-CLAW Djangoshgs3 ?E, ~~&i&%~8if-4Gi~RZ%?~0 %S~~Z*%~F?~J~JIR@&?&Z~~~~~~~~~II~@~ Django $ #fTjRgHHmIt;~S+idf+, G%qI:ASf$$%H, 6%WlJ%Z%Zm "contrib." ER@@kf+, tLijftniAiiE@2, Egf$,$,qU&NDjang0B%*;f;2~ from some-exterior-auth-lib import get-user class ExteriorAuthMiddleware (object) : def process-request (self, request) : token = request.COOKIES.get('auth-token') if token is None and not request .path.startswith( '/login1 ) : return HttpResponseRedirect ( ' /login/ ' ) request. exterior-user = get-user (token) class TextFilterMiddlewarelobject): def process~response(self, request, response): response. content = response. content .replace ( ' foo ' , 'bar ' ) ()asuodsayd~q~ ulnrlar :(aqenrrcTmoqs 'Kep 'qr)uom 'JeaK 'rlsanbal)aarq~xe jap ( (awu-qse~=qqysqxeqsy-qse~) xa2Trj ~sq~a[qo~uosxad=qasdxanb 'qsanbax) qsyT-rl3atqo uxnqax :(awu-qse~ 'qsanbar)q~xeas-aureu-3s~l Jap uosxad ~rodur s~apou~ddeAuur.~~a[oxMu uoxj qsg-32afqo qxoduy ~reqap-~sr~'2~laua6.sma?~.06ue[p uoxj qxodur sq~ne~ap's~xn'~uo~~o6u~[p uoxj IU%-,I Q 2% 1 #-H 6S4k!\ @%i& &&W@@g, RG$$i2 ZH@+$U%~&&%&&T-%~&%~ @%R#fiX%2 %@RIU$%lYJ, -H%4i%S 6 &SL?!2!3 Django8*k$k6R3i$BfimFE$l7 {HS G%)&fZ@T-%@@ifi$%l %,~~~&~j?$~django.shortcuts~~$k, render-to-response: &+&j&@RTE$FUZ&$JS@, M-G~Jg-+Context%f$@, $!$% HTempIateB%, @G&El @,$&~!YjHttpResponse, '2j&%-'i'-&&!B&$, -?q% lYJcontext3$$? (&qU%$&) URMIME%%, 8% El-?HttpResponse%& g&G %ea%6$%fiiBo Http404 : S?ExceptionT%&liH -+HTTP 404gi2@#HE@-?@E@404.htrnl#g & (%4k$$&settings.py%Z52 ) l%ffl@%$~raise%%B%?a"1'r.L, fit$, ,%U%$%E $U-?404@R#E, G$k%-~&l@@Bi%, %$R!~XH~-?$~@~u~U-?~&kW - %?%$ZX$Edjango.http@kk7;. get~object~or~404~Rget~l~st~or~404 : ~fi~@f$?@&~fi+g@QZ%--- : $%fG-+H &&~~~JZ!? $~%5!5~%k~!lU~~Http404~ '241'1#53-?klassB& (?2#%3% %&@ ?2-?@2%, -?Manager, $,%-?Queryset) $U-%&B&&i@B&, Dj$nBPE!32 {*S%~anagerfRQuerySet@$&, 8%@~~&%~~&&%~~%o ~g%E?@RS%%k@?i&IFJ@J+: %-+g@@HHttp4041 ~~%I'PNIJEZT$U~H get-object-or-404%-~~j&~J$+@3 El &-~fi+@&&~k+FPf'iX~B#HH. %$2$$ 32@@&@$2, &%632&i%%&f$?2j~Ifl3 i&2.%FZ!J#d!~4045?$H%&: from django.shortcuts import render-to-response from django. http import Http404 from myproject .myapp .models import Person def person-detail(request, id) : try: person = Person.objects.get(pk=id) except Person.DoesNotExist: raise Http404 return render-to-response("person/detail.htmln, (verson": person)) from d jango . shortcuts import render-to-response, get-object-or-404 from myproject.myapp.models import person def person-detail (request, id) : person = get-object-or-404(Person, pk=id) return render-to-response ( "personldetail .htmlM, ("person" : person1 ) O%#tf8ZQ (M6S%ZM%t "HE*,, MY&3U$l@) 3l#M%@B#+-;zz+j%gM%lY%3%4G '3H%WT g v* Z7&$$4;itF%k%9 " L&~@[ll~a!~!lua~!llls%l~~~HI 53l#MZ%2BEI 'BH!kd#r/+lY% [,pr--)saCqo,]sBle xo [o]sBle -63 02 xajar ues afi araH # :(s61emy,, 'sBxe,)na@u jap (% J03PUJ 8) <117/> <@A/>( ( .o~'sax. : ousaAl a~qqrp~~-sr .uos.zad ] ) <@J/>(( aun?u.uosxad )) (B ?sy~-uoslad ur uosxad 203 g) iaIqe~yPAY aur~~ R+EH&&%&@afiH%kh@o 1% block %)s-'?@$k%@J%E, slTUm%$x@&%@&it:$b%%rEeH&&&@ %ft9/JlTo ~%#&H)LT&B%%P&EH%!M (block), BJ$%%+Z~%ft90 G41lqU @i&,B&% (S#X#%&E&itke%%Z%4th) &~~-~~@i~~4&-EH@&0 TfiS T@$H.5piJ+@H ~~KJ@EIJH~ER$&$E~, eHURLg/, /sectionl/, /section2/, /sectionl/pagel/~~/sectionl/page2/, 4, fi "Rt-9" BG0 332, base.html%ET DXEHH%%.t;5, sectionH#%&Ei?!7fi&Ht%% (+&M 7H P%!d!W2Pti&H!JP-%@), fipageH#$#illlf2@7simple content, base .html: (% block title %]My Web site{% endblock %)
Section l Section 2
This is Page 2.

(% endblock %I Section 2 < / head>
&&%&mR,6$k&TfR73%&@&E&LE~B%t%FUitkE&&&7Ei~%XRKEm @P%~HTML, k91, ?uSTB$~~~~PH~&~P&G+~~~EB%P%B&~E, R!@, &g% RW~~&~C%X, %&$&@lgii8fR$RWB0 &&&&@+i @9R&B&GSA$K&, 62&&Ei%@fiGR$E2ii!l0 ~H!Rb%%%sMm-& HTML&%$$2&4RfimR&%&m%B, bL3u-+%H~5j$fZSo Djang03%{% include %}&2 (H&Z&qU%$U), k#@%&&l%#~&*!41%%$7 &!G&h Z%$%&s +*!4b9h2$0 &&*!$El Z$kqLJ2-+Z%%%mDjango+g&, kflWIhSEB@B&#g &~conte~t~~~~~ B 7 {% include %),DjangoZ#Eg 7 {% ssi %)&E (sZ!%ssifi5J#J Apache&&mSSI, aP&%%$$@,$, Server Side Includes). {% include %)$R{% extends %}GI ma&settings.py B#EX~tem~lateB3+X~~E~@&*!+~ mi{% ssi %)EHKI!~IS*!~%%%H~$~P T 2ic7722fSlia7, {% ssi %)$h[;R$lf&-%$+Zb9 B $9, GqLJB2settings.py2!42m ALLOWED-INCLUDE- ROOTS$^)^^, zGZ%&&{% extends %}$R{% include %)&%~CJ@~context$S&B~~~~~$, 3 $k%T@&q~$&%l&%ki~l%&&~#~&&2h~fk$g&%7% To ()a~es.uosxad-nau .sqaaCqo pa2elal aq2 # 1Cq pasualajal aq ues pue sJsyxa uoslad xno 'ga aqa 02 aAes am 1a23y # (asIed=qyunuos)a~es.uuo~ = uoslacrmau ITT~ paxxa~ap # axe daq2 os '~u~od srqq qa panes aq J ,ups sq~agqo pa~e~al asoqL # (~23a~qo-paJe~ai-b~~pn~5~r~~nduy)~0d~os~ad = uuoj 'p~ayt~Aue~o&Aue~ aqq ey auo hzemyd aqq 02 paqeTax sqaacqo # uosxad Ieuorqyppe 103 .suuoj-qns. urequos ppom uuoduoslad oq qndur s~q~ # ,~a6uea, = a~pp~u~uosxa~au *uosxad panes-un Ino uo aqnqrxqqe rre aqepdn # (asTed=r)Tunuos) ams xu03 = uosia~au .paqanoqun ST asepqep aqq qnq 'qaacqo UOSXad e qa6 aM # from myproj ect . myapp. models import Person class PersonForm(forms.ModelFom): class Meta: model = Person exclude = ('middle',) 4nR-+PersonR&first, middle$~lastZ+gE, 8[37;fiHfields~~~Df+~~k~Z~zfi ab &-#: class PersonForm(forms.ModelFom): class Meta: model = Person fields = ('first', 'last') ZgZ&Sm4E%SZm--,6Z9 %iMMZ#~S&~save3%H, eE&iitH@&Wu ixmg5ao 4~~i~~~~7-gggfi~~ge{i1x~~fi~amazgie~~rqg~~ ~um #mlff;E-ZZ@E@Me{I']g/L,@&&%S;r%m (null=True) , z/L,&defaultB&gzX 7 RMl8, R71&ZZ5$%&2!.!E!~@P!!2~E, 1&3~USSformsE~~Field+%, %fi%%iEjQ 5$z%Zm$5ao #%fRfa&, B%5$&aZx%4(l@Pq, i?it&&*$8Ama%B~l&8P#, %e $ &Z$M@ZJ!U@klj%~ZK, SRi'.f.Kf&!?&E!%Field (tk4nmax-lengthgrequired) ?& $-%{&&%*$j (s;l$~~Z#ETextField5$/7;%CharField, X$&&i%fi--+CharField$& Choice~ield%#$~-5%%%) $13fR%ia]. fihh, 7;fim1PIJ+$hE%$gBm*B@%7-T6 : class PersonForm(forms.ModelForm): first = forms .CharField (max-length=lO) class Meta: model = Person &2s!8f*-?,@?lj%$$%?f&gZ (relationship form fields), ModelChoiceField~U ModelMultipleChoiceField , G{jl~XIj2t;fForeignKey$~ManyToManyField, E,@fi$SiJU&fg?J!j EgEgtgZlimit-choices-tog&, gs{&3qU&CS&EgB- Q Z-+querYset&& (@ Q%l%, G@%mj%-+$+$mQ~erySet3t%)~ %#, !G$kS;rl2&C~%9EE~i2+E%~l (?& @) #k!. i. $XModelForm, ~h!&T~~lfi~T-~, %40~~i~Pesson~%2~-~)~[;i]~~& PersonRi'%m?G&bR$!mXForeignKey : # A normal, non-limited form (since the Model places no limits on 'parent') class PersonForm(forms.ModelForm): class Meta: model = Person # A form for people in the Smith family (whose parents are Smiths) class SmithChildForm(forms.ModelForm): parent ='forms .ModelChoiceField(queryset=Person.objects. filter(last='Smith8 ) ) class Meta: model = Person from django import newforms as forms class PersonForm(forms.Fom): first = forms.CharField(max-length=100, required=True) last = forms .CharField (max-lengthz100, required=True) middle = forms .CharField (max-length=100) class AgedPersonForm(PersonForm): # first, last, middle all inherited age = forms. IntegerField () class EhployeeForm(PersonForm): X first, last, middle all inherited department = forms.CharField() class SystemUserForm(hnp1oyeeForm): # first, last, middle and department all inherited username = forms.CharField(maxlength=E, required=True) Zqu "&en #%I$, RPg?&f %go class BookForm(forms.Form): title = f oms .CharField (max-length=lOD, required=True) author = f oms. CharField (max_length=lOO, required=True) class InventoryForm(forms.Form): location = f oms. CharFieldO quantity = forms.IntegerField() class BookstoreBookForm(BookForm, 1nventoryFoi-m): # Has title, author, location and quantity pass ((woj :,woj,) ',ylu~q~wo~/ddehu,)asuodsax~o~~xapuax uxn2ax ((,uqor, :,~sxy3,)=~ey~yuy)lu1o~uos~ = woj ,pa22yluqns sen Kuyq-~ou 'woj aq2 he~dsya # :&sod'qsanbax 2ou J? :(~sanbax)uuoj-ssasoxd jap (~so~)K~o~uosx~~ : UOj (,uqor, :,qsxrj, ',aoa, : ,ASPI,) .K'a # ()hd03,&~0d'7sanba1 = 7sod :(~sanba.~)woj-ssasoxd jap .suoj-iep~~e~ paITej 10 s2sanba1 &sod uou 10: mro; aql AeIdsTa # ((-ise~'a~~~~~ar :,qse:,)=~e~q~u~)mloduosrad = mroj ([,p~,]sBle~y=yd 'uos1ad)pop-ro-23aCqo-2a6 = a~ye~al :asp pa~~~j-a~d aATqeTal aq2 qqrn mloj Aqdwa UP dad 'aSTMlaq20 # (()~rn~aqn~osae-qa6'uos~a~~au)q~a~~pa~asuodsand~~ urn2ar ()ahes.uuoj = uoslad-Mau :~T~PA-ST'U~OJ JT (&SOd'qsanba~)uuo~uosrad = uuoj :&sod '~sanbar jj paxoa sen unoj aqq jr aqeeTIeA # ahTqeIar waled aq2 2a3 # :(s61emy,, 'qsanbal)a~yrle~al-ppe jap /ee~/u~~e~~~~l~p~~luos~adl :?all S,Ma:A # ((ULZO~ :,uIIo~,) ',~u~q'~~~~j/~~~~ad,')asuodsa~-o~-~apuax ulnqal ((2seI'aAJ2eIal :,~se~,)=~e~~~u~)~~o~uosxad = uuoj ([,py,]sblemy=yd 'uosxad)pop-~o-~saCqo-~a6 = aAT2eIax :&sod'2sanba~ qou JJ PaLSOd SeM 6UJq20u JJ UUOJ aq2 deIds?a # :(sBxeny,, 'rlsanbal)a~~rle~al-ppe jap lee~lu~~e~?~~l~e?~luos~adl :1xn s ,M~JA #
还剩288页未读

继续阅读

pdf贡献者

air_cc

贡献于2015-05-28

下载需要 8 金币 [金币充值 ]
亲,您也可以通过 分享原创pdf 来获得金币奖励!