0% found this document useful (0 votes)
34 views42 pages

(FSD) Module - 2 The Django Templates and Models

Module 2 Notes of 21CS62, And 21CS61 Textbook

Uploaded by

Amaan faroqui
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
34 views42 pages

(FSD) Module - 2 The Django Templates and Models

Module 2 Notes of 21CS62, And 21CS61 Textbook

Uploaded by

Amaan faroqui
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
Ted ule — 2. eli The Django Templatu 4 Models Template System Basich to . is Q Sfxiog A foxt Ve A Django Leonpl ase Tottiadedl ee Oo aes coun Prucntatoo a Aouiment from is elata , Alp tecepleke clGinin glace Bola saps a) altos loits Of basic logit. Ciephplade tags) apusd recguicte should be clispleuycol, A) Usually, becopladn ose Use pen [rd KML, but django templets se equally, Cepae pets 7 ony Lint baud pormed « Let'us tale simple cramp € duscsibs ao HIM pleing an how the clouumeat {ern plate , Poge WHat orcs with Cx y his, kenplett ehh ol [pison pba, I Company , Kbtad> i

Deas {i pusee — Pare 44, xlp> ; {faye abe io item _lest YG liv ititem Uy

  • ill Templake Syntax brror Exepiio + | per prom Agogo. tex plate Yous i 4 : en pot— mpl ate Pe te eel Gi ov) | vacdouck (Corost vecenk Coll Jost) ° Eile “xs tte Sy eae I Ayanyo template. Template Sytantaror » Thvalicl q ' i bloke + + Notateas | dg d Rares ooo Ae, Terplete Synbax Err excpt'or, As Sa ey sSias yong Meee aie i + Tvalid blode teys + Tavelid uments to Valid blede tags * Tanalid pitters * Twabid unurks 0 valid pits ‘Dawolid Feaplate Spofart ‘ ‘ilove Uorle peas (pee blede tap: opel gates Scanned By Cameta Scanner omplali ( you have @ Template object, ou Can puss if i 5 givioy it 2 Gottrt data ky git (ewe ae a gry a sho, variables 4 theiy abe values, ‘ ( usu this bo! Peputate tts Vatiable togsg assodi A A beemplete evaluate its block teys: f AP cootrt is repr aeoted Yo Django by Contet clas whith Livis fo deat Hanya. teenplede . rocdule. pr Tis @omlrufer dokes one optioned atpimerdt’t a dieiierey mapping Gaslasl name to Varbbls Vad wi» A Call Aue Teemphte object's ~eacky() method with OM Nesp ret tel il (ei Mat ae yeaa Ajango. template Feppecet Contest tes $e Template ( nae is tt mane 35°) = Coot e#(f “nant” 2 AS ne te wencley (<) ai %) “My Nant is Steph oo’ g- Notet- TA \lariables manus oust Beyin with a lutte(Az OX) and erty Contain Mixits Unclexvcors 4clots Itt \ewablu nanus c4e* Cadtsersi tive | é ie Scanned By Cameta Scanner ‘Scanned By Camera Scenner *

    Pes Tohosrnith, \o\e

    Thaoles for ordbe: Super Lawn Power prem Outs cr Elept ee THs schluled ln HH ship of Apyi| een \n\n lr

    Your bo PHO Will be fockucked inte Poueagiot « @lolo\n The fh pow 24 ta sifs 0 THYIE porloo p” Lécoplate _ Loithie Phe! loop! 4 ) » ottributes thed give you in fx besa 4 ahis variable bat a pus loop Altona ee oeeDemmIa io. 2» Blo ab fnttsex weprere . berleop: Countty fe js alwoss -oting Hur no. times the [Bop hes bur ected, ished Gil fiber tela tesa 4 * {fibres 43 < IPS }

    tf ppr loop, cau otis {rend go 14 het, porloop. Counter will be oct Ce 4. ° josloop. Couokerd te fs) fikefeldOPp. Courter: only, excel it's saese inckerecl , Me value will be set to 0.) | © tovloop. vevcountey se%s aloays set te an iokeges ~eprcicoling the nosey steneining iteons ip the Loop e foxlwp. rev couctesa so ae Nike perloop .mevcoupten, cxcept This zuv-indend . e powleaps piss refs a\Boleas Valu Set to True iy this is the pinst Lieve Abrough Be Loos? |) © forleoprlast te isa Booka value su to True tp this q jy the last toe though | the loop, a 3 ieee | ignotequed 22 0 A The Djacga teaplate glen deliberately” is not a bull pledged programenigg laguagt 4 it ds! not allow You to “execute asbitvary Pichon statements | A Howeves its a guide domo template fi 0 Ke scequivemed +0 RA Boo values 4 dlispleay somethin ‘py thy ate meee) ime Scanned By Cameta Scanner BA The auguencols 1 Sioglt oY clouble yuete. Ets yHi a {igual secbion “Gomer Abi> Bomonrity LI bi> (1. eodipequcdl hy BA Like Tip) tag, the wae 2 ophional fF r/> cbse + Tai $fipequad section ‘sien, SiteNecos tajs- ; 44 mg te [ecapel eee maids X took Mclee 4 bis Ie vosyt a, alten ag the Valeu y Seone filters alee aaguencalh 44 biol Lyuncattwor ob : 30" 34 ? | { oF a This displays che 14 words ) ur bin vaeinblo ih Filter ayurents ase a cys 19 clowlsl, quotes. The ppUlecoing cue [fo pro ee Pr pilters Ce oddslasnes: «[Link] backsleah byere any badkslash, single quote oF double quote { d dade *Forenats a Wate er clatelgMebycctl akeoncliy 70 = Gerenat Sri | given fo Pasancebil © Qi tl pub-chde fate 2° 5 Ye escape 4+ Excapes cunperscncls 9 uohe 4 angle bradeds Ss Qos givin shin | i Sptepicatty Ccapep Maku, These WeFSIO ag» — # Gveris Ado saenp te Qovels < to $1t A Cones S4o gts ° ab Goverts “(doubl quete)do 4 quot A Coprests 'Giggh quete) to diag: J I | be Tenth t= Petuins ou bagth % dor value. Yor con we This on Ust or ctortags + Toteracting with % Detkobase: Models. EB ) ie FS) ti Developroert Pattenz> . (5 ) easlict, ee’ iS Auigned to E a As woe mentioned ation bho Encourage {oose Goupliog 4 Strict Sepes Pircw a a9 application © 1, A Tn Views pucchions , We as Ps, the ienport ance ) ose ek pracotea Bepasationg the businss sic ~tivd legte by Uiiny tencplate sydem. Wil database loyer, ub ase applying Hit Sacne Philosphy to edcedu retard ata access logic | BA Those thyee Pieces togtther — clata accus logic bushaus Logec Pracotat ion logic, This Gocept ts called Model —\[duo—Gatroll er (TIVE) pallers my She cachitetase, A Tnythisy Model > “reper do ote ada’ accts layer, Alito, SS cvenaym $0 oe Past io, aie eta ated ceils had to Aicplay 4 how to Lisplag « .. Condereller > repens ae elects Ughich Vito FO Use, peti postin usler il Bicone ae mod) | ad | nected . ate path a quns ystem ‘Scanned By Camera Scenner ‘Scanned By Camera Scenner aay | Teoplate Lean x Django provides a Com picot & powerpul API per loudreg temples fa aAisk. A trondee 40 usc this Lempplate) loailiag APT) 1 yo Ped to tll Ahe framebirvl where you store Your dreopletes e A The place te dovthis sig 10cm a A Droge schigs pile is the place to put Conyjigueati. per you Djanye | Proyect 21% A Wheo you Tun [Link] cid roo. pry stastprett royslte, 2) script creed a aleyautt sub ings: PY pile 4, woos Vetighles fiat took tile this ¢ DEBUG = True seltiogs « Py pile. TIME one USE _Lign RoeT_ UPL. Con =‘ ak A By dqaut, tre TEnPLATE GPRS sill be cory tecplom jou would Like 40 S10%t Your ~pree tg where Lentplak $+ FEMPLATIE—DI RS = i " A Dealt pose tue comma tata tod o» the termplede diveckory ssig The Ppylheo wey" Genmrgs withio Single ~element™ tuples UP clisarnboigaccte alta. 4ucple pron par cothetical emp sion ‘ you want avoid ewret, you Can nuke gust a, emt Are DIRS iS a Mi foatead Dh tupla ste rempuaTe- Dias = L hy [orga] pevplates ‘ ‘Scanned By Camera Scenner ‘Scanned By Camera Scenner eee Suit Be a tania o iaopreh Terminal Cott a prt HtpRespoe Sie aja tecoplate . roe Ares) pip i eee ates d datetiore Coast oleh eee pow salateimne « dleute tiene MOL C 3 Jes [uses] Slant [project Lyppl fengplede] mayen gps opeo MGs oD LeTeeoplatt (prea! » bP: dose( Mh bid = vente (Ct ae: | nui p4tp Respoad tat) } rs ioeleqa? peor thue reasons 4 This ap prach Th clounit handle see CFE OD | a file. tp dew pile roy feoaplcte otal dodott exid ov is por oreeclable j [Link] 10K rer exuplion . ae opto) Call will te toceetion 2. TH hae cocks your tererl ey borlexplede cael) . ae tadudes a lot % EB Scanned By Cameta Scanner Template Traber tanct 0° 7 rey ot PL loasic tecplate examples °° por have foeco io cal coord, yout UW be hrmL soippets, bud yo at ar exreabe ee Djargo's template sys eee do usio enbine HTT ase, thie [eects fo & Commo ftot> eluloproud Forolltm across 0 WwUbsite. thea isets clo you apeduce Ae Auplicd fm ae ee Common feoge aseads 2 BA PA classic wary % solvi * sexver —sicle iochiiclis” te Airective which you Can within your HTML page to™ focluct” ayints problem ts to Udse combed 008 WUepage Tosree another A The Django Supports aunt approach, wil Phriedude 7 Jteenpak (eg bid preyed eg MH solving CHse | pie bb woth Django is bo Use a more ehigant stbadtgy colled “teenplabe Taher banc’. b fhe FPilds see an example n, this boy creaking Template por SUtdeot tabttinn View .— iy Scanned By Cameta Scanner ‘Scanned By Camera Scenner ——— Ia With a0 Todlude - based sdoattgy , heackys 4 portent ake CO A In bud tbat title can't it A Djanges Femplate fohewé probless . » bul Tey is ali te rend: di fone bitle is Aipperenk. example » i oe Rate ant eine colvs Frese «Pious Step ts bo deine hase template -o sletttoo Wes ipaye cued child template ravi tater pel in. a Here's a lease Lewplate [yor (dus orgorag cong A yee! Pe ' d J poct4 Pé HT™MLS % Chbnil lang 280075 / |


    { ‘ T-cdblodc yy k Here's hou i+ -uporks, IR@ YOM load clue fenapl Current dabedi ae rind template -egyine seu Viectencs Yi jtea ths Cofine ines aes loase, hte A Nott! child terplete claunct clipens poster Sirk, T \ \ fae chide! template Ye ' oe porced te-wplacte Pa i S F : _ pine tS tho 9 ) One mere Haz > wring foheritance 1S q hollow three-level approach: Na 4 fe Create a bose. htoa teenplake thet betel the mein fool + peed a yous gite- 9, Cxade 0 Bate “secrioN- hinel teenplate “section you site . The teeoplatas extead lease bind A jodude secon —spuipic stylus ldaige | 3. Create tnclivirchecd Ecoeplectes per cach ebyeet type page Such os pear pege 2 phote gotteg. yr cach > Here ase Some tips por working worth template ioheri tance 32 Ie Tp qou ute GrexkerdlaE) io the teonplate it cout bee Fee \S# bernplete ile fo aad tenplate ofherroise Poherdtanee Wort gor template D. Conrally y the crore {I bleck 7 Y tags in yous lrase temp 1 i ; — bes ls bef bey . but yemembcy cha templates Sloan have to Aepioe alt peseat blocks ]3. 5 you pind gousey Aapliteting conte Ym peop templates te probably encans You Shouwtd move thet Coda ffeblock 7.4 in ay posed template . untet YO ga da thats a, dee block prem Ti, yo ae Leacplate , ereeumme HE Super gyro l aaa dao He trick S. You moy not clita nualtiple (Yblode vy bogs cord ate ait | inte RI Gf. The eplaks Nowe You pas to EYiextead 71) i let) Te eee pabliceim cot Ft terplot Ud, ' 5 the augue 42 Pfene Biel ae L wi be asf, be Ke can op, kta ‘gy Re 5 Scanned By Cameta Scanner EpTovlalling tee Model 2 = a) ee oe fable a te cus Create to 0us dle, a0 de thar \/ IF we med to achivede Ahese mods fo Dean Project. ‘ "i the books app to ae at ge, redo thad by addiog Iss Fastallcd apps in Shah pile. Aw” Edit hot seftigs. PY pile again A look por “e WSTALLED. APPS. Ths fells Hee Django vohih activated per ole given project Pps ost sont Ulee Haast a By Apart H loples Tsuen _ APPS = ( beauth!, cooly ‘ ot enttTe sy ‘Ajang o. sind! + SUSIOnS, | \ “ ote, Catal “misite. booles! 4 A... (oe — moods Che (oasis to) Salutation biking nd = 4 " 5 fest _nane= 4 Miter vedda. Eadie ° ) readihel = models. TraageRv cplagel to =! Hp) ja Claas Bogle ( rveceds Meld): be fad CURE (aati authors medal, Mang Hae Held (Audie) Pabwher= mods . CAgdeotl Foreign (Petaker), Pblicabinclate = prodek , Deke Bret c') each coed ripen abesl bya pron Ab. mods, Model. ss Us caer ce Class thab iis subdass ay ange ae Each model Corresponds fo single dedabase table + cath adtsibuk on a Medd Grrupercs +9 Chinn 10 ono datstour teble . The oftvibalt Oat Covrupencls sho Columns mane & Fupe a, peal (Ghars itd Grerspercl vo Al Columa type (Vaechan) 4 Cute Publisher onde is equiyeled bo polerig table CREATE TAGLE “Leola —pubtisher” (_ “jd” serial wor Nu PRIMARY EGY, “pant” vaschas (20) NOT NUL, “adelrus’ Varchos (so) Nor WULL, “ag” Varhal(6s) Not NUL, “Ske? vaclot 3) ) > ps Fublisha (rarne = 'Apwess’, oddeds <9 gsr Tekgs peid re Sabieg uo nbly calls 4s save) yp Bill Save Ae sccord 10 place without ~ Creadt 2 pew Becord . >> Pnare = Apras Fablidhtes’ >>> psave C) A The preceding SONCC) Stated coill yuuth 19 poll sale. UPDATE Look — publishes SET | rant ="Apeus Publishing’, E addyuy~* 1 ee ress Tdagaph sae) ce Stok = ae Bie wte whe verd= oo} \ Scanned By Cameta Scanner = Selecting Objects 3° * The Djeoge Bosal ZENS BLE CT when looking up clata A ide hove seone enebhdate T) Filtering Dokase f A bWheo petchis all objedls cevioumly bes is uses, mast 2% the ive woLlase going to Wak total with Subsd A deta We clo De oa pitied mahod . DSS Pablisher . objects + pibie(nane Apres Rabtubray”) [ePanwikes , odes Repusbiy dd. word aeigucocd that ges “ly aasledted Clohere claute . ky + D pitlerC) take fk apte into ew appropri XSQL Ext Sdeck fot, nana, Coty habe, Ct Bey , usclasit ¢ prem book =peblshey i coheye names Apo. we Ys can cho poss routtip! doy Publisher obyects -pi Hey CcoenBry “USA ‘ thae matbiple oitgunsenks gus frantleticl info SAL “AND? clause , i £ seleut was! Paslishing’ * Je cergernreabs inte pitted sifete =a") R counbyy , ebsit¢ , | prom bovle— publiler where Counted = cy sAD AND, Gtebe = "cA, A. Some lookups ate owdiifeble : | s> Publisher obyee ds pilter Comme Contains = “prus!) There is clodtde’ unclerivore ble mane 4 Contains. Django uss Aowble «1 to sgt phat something Npaagte” a's ope ha fret angi, Tet gts tsanslabed by Pjango iret sat Like! sdk “id, name, cety, hake eoutry pFom book F name LIKE“) prust.” 4 cok publi bay, other lookups ovarlable — 5 9 endsusidh range bi~) @ Scanned By Cameta Scanner ‘Scanned By Camera Scenner QWs poe A This order pbk shots, ‘Scanned By Camera Scenner => Your Frost Model se (4 A (Uw take example 97 % basic Pook) aetebes Publisher data layout . ble use this example 0: the Concystuad relatioah, bl boots ,authors + Prblithes ate wt knaon & We'll Suppose the pollowies Concepts , fictel 4. prlakionships: © tn author bas an salitotion (Eg: Mr ox kh) 2 pirst nana a last nore 4 am ernail addrus 4 2 headshol photo. A publuhes hasa pane a shret acldress a ct a state , a et Aa website, * of book has a file, and a} publicction'd ate | TH Qe bes one ae maorp | Obdhons (a many Ye ony “rte onalutp Lope. (elutes) 4 sivgle pubtsher (on fo many ee feredgo buyin to pettus) A The | skp ts go ¥0 Stapp Command thar u wil B biel mock py fib dalenter Chae pallor! a; fron Ajango. Ab import 4 jocdehs class Rebtaher (gredebs rode) : mace = rpodels, ChavFrtd (grueling = 30 Gddyas = te " oe) city a u shud ey = ' oO re ve fe Qury - . eel ut mote sihe Se eagle UPd y Scanned By Cameta Scanner Youre Fact Fppse - x Djerye app 2 bundle 3 Dj2Y? a? ‘aaa oc la 4 Vits cfd liv together io oO siagle Father padeye ancl that weprucsts a pu Django Opp cation . BA The Lyperne blo a projet 400° pp Se ep Project is a instance] o Certain seh Dy D970 Apps, plus the Conpigusation pos thor Opps. Teebnicaly) the oaby requirrerncot oy preject ts (edt itsupplia a setbings pile uohics cine ae database Gonextion inpo, Jit my installed cipps 4 TEMPLATE DPS, * An opp ik a portable st 9 Django pre eo ee swabs ML Frdladts | erode 4. vicdos thet together Lives in a pine Pa thoo fradeage | BA So, we crrrakid a pile called Views. Py > Ts piled Bwitha i View function 4 poroted Loy VPLcanp at Shose [ypcttoas oF BA Buk, ip cou ate Using Djoryohs clolabase | ayer (anes) Mou must crcabe a Bango [opp . Plodels mat live within apps. In orcley +0 staxt voriticy ue models, we pred YO crete a atu app. Syabari- pydtron prorsge Py stakepp books | This comand cles rot provide 7 elp bub SF Crude Q bool director b Mae nite Lived Bh Ti Galeb mids ciiteciovits PME te ¢ ‘ Bs here No “opps” Wee nee Fait PY, Scanned By Cameta Scanner Sathana: (KS) Chang lo «Bi Datetsare eT, You ockl oe change Be rouddb’s pid os ty 48M Jebite @ atu, yor need Eto crake toe chacge io your celabese mantalty | ole ig wilh sdhenge changu it is ieop- te a tw things fo coind ode jreuw = Daogels | eleatedbase fouyes woos ka je Will” Compleri lpaey th model cootacrs a pyetels [hat bas nol yltt beco Created 19 & clatabase dable, This will Cause an 0 +X OY, + Django cow net Gare 1p & database table Gotains columns that ase not Ae Coed fo the apcdel . Django clos not ce ip p database ids: Contains a table thal “s ool veprescsted by @ model, A Mak Scherna change ts a matter > changing the Vosi Oud preces 1) Adching ere lelaes BA Falk, tele these Steps FO development eavirenaxal +. Ja. ofeld bbe pill to yous Prods Ran Mancye. PY sqlall Brorape) td see the nee CREATE TAGLE Statement ‘pen the cred ed ©. Stak your clatabase's tokesaclive ohett Eg - fracayge. py Abshel Exete an ALTER TABLE \Stcttionat thot adds yous Nu Column. De Aloh Aya tebe Ac th ve abl fea ‘ A. O pho! ) Piéady Launch the pythen iqteractive Shatl wit pris shell A yeuby Stat nuo preld wos addled propuly MH imtPortiy ape Mode! A seleting prom ax, hab Scanned By Cameta Scanner ‘Scanned By Camera Scenner A The nw Colum js refracted like thi! Spum pegs” Tokeger A Next we stark clafebuBl fotevackive shell ous dueloepmeot cletabos © A carcite pol. stateme als: ALTER TABLE books_-S00k “ABD COLUMN num _pages Toluge 5 OA A pier dic ALTER TABLE Bialtre, We'd very thet H te change worked properly Jog stautteg (Eh, pyvte shell 4 aranaiag Enis conte: De prem siLt . books pdels fropert book, DS Book. objects. aC) Lis) rt Ty ‘this code didn't catire ao) Cru then switds +0 ous produciioa server 4 Cxbcuke he ALTER TABLC shuteus dt ogy cat prvoclent Ome Thao s Cae O Wag os Me Meted Ate pote. prrockt im COV i veo mend) A. yutart Alu web SUtVve 2] Kee Fictclss. A Removing a picts rons @ erblelil cL eee an cicleteng 09. To Beoreve pidel jest pe Ueu ter steps. > | Is Reerove the pid prom iyous model 4 vescut qere f Webserver, ‘ SO. Panreve cttw ele by @ i@mwand), Dttlecwiectl ans ALICE ATBLE books! book ppop coLyrahh num p9y om vou) Aatabese, ae 3) Ieermovig ae bo [ Mecng Fretds: = A Mao -to-many Fidds A pecot prom normal pidols so Abe yermoval procs 2 abepyexerk: 1. Biteove Waar Many To Me Fretel pres, Your onde 4 ccudart Hue Wubsuvd. ¥ table prom yous db, 2. Remove the | meny—to mony Using a Command lilee thes + DPoP TABLE bboshs bap pibleshess 5 4) Removing Mocdeb: >. c w Permmov Bs eoodel eal Cas} as remowng o 5 g b'AF To wernove & Vepoded Gust pollero there shes | Pecwove rood prom Yous model py pile + restart OR Wud sever 2: Remove the table prone Yous datckase Using a Commanel Like {hiss Deore TAGLE books book }
  • You might also like