Vous êtes sur la page 1sur 74

12/23/11

Relevant Links Django

NewHere? Subscribe|AboutMe|Twitter|Contact

Sandcurves
BloggingNuts&Bolts VernonSwanepoel'sBlog

UsefulLinkstoDjangoBlogDevopment
Acompleteblogengineusingdjangoin60minutes Thisisagreattutorial,andfollowstheDRYprincipalvery well.Iworkedthroughthistutorialandlearnedalotfrom it.&nbps60minutes?Ittakesalittlelonger,unlessyou reallyknowyourstuffalready. BuildamicroblogwithdjangoThisisanotheruseful tutorial.Ididn'treadthroughit,soIcan'tsayhowgoodit is.

Sandcurves
AdetaileddjangotutorialblogbasicsHeisanexpert, Iamsureitisgood.Ididn'treadthisoneeither. DjangoTutorialsAlistofDjangotutorials. TheDjangoTutorialGositatthefeetofthemastersof Django,andbecomewise. Django'sDocumentationIamsureIdidn'tneedtoput thislink,ifyoudon'tdipinthedocs,forgetbeingaDjango guru,ever. RunningDjangoonGoogleAppEngineFanof GoogleAppEngine,herearethedocstohelpyouget DjangoandAppengineworkingtogether. DjangoBookThiswasthemainthingIusedtolearn Django,andIfinditreallyuseful. DidyouwriteagoodDjangoTutorial?SendmeaTweet @sandcurvesandI'llcheckitoutandstickupalink. Hereareafewotherrelatedthingsyoumayfinduseful Emacs ThePythonTutorial
NamibiaI'mapassionate blogger,computer enthusiast,naturalistand fatherSandcurvesismy personalwebsiteandblog More Home AboutMe Topics Contact Blogroll

About
My nameis Vernon Ilivein

BloggingProject
MeaningfulBlogProject Linuxandopensourse

sandcurves.com/blog_engine/links/

1/2

12/23/11

Relevant Links Django

DiveIntoPython[outofdate,butsuperforlearning Python] TheGimpImageManipulationProgram Ubuntu ApacheWebServer ReturntothecontentspageoftheDjangoBlogEngineTutorial

Tutorials
BlogEngineTutorial

KeepUp
SubscribebyEmail SubscribebyFeed

WriteOnSandcurves
GuestPostonmyblog

Work
IworkatandBeyondasthe managerofourWindhoek office.Ifyouwanttoknow moreaboutNamibiaand theandbeyondoperations inNamibia,visitour Namibiapagesonthe website.

Ads

Don23DTrailer
NowPla ingDon2Trailersin 3D.CatchItAllonYouTube!
outube.com/Don2

Sams ngMicro a eO ens


Deep&EvenCookingwith SamsungMicrowaveOvens. GetDetailsnow.
www.Samsung.com/in

Copyright 20102011VernonSwanepoel|Djangopowered|WrittenwithEmacsonDebian| HostedbyIntegrit Namibia|Subscribe

sandcurves.com/blog_engine/links/

2/2

12/23/11

In od c ion

NewHere? Subscribe|AboutMe|Twitter|Contact

Sandcurves
BloggingNuts&Bolts VernonSwanepoel'sBlog

Introduction
Note,thisismainlyintroductory,soyoucouldjustscan through,makesureyou'vegotthestuffyouneed,and headontothenextsection Blogger,Wordpress,Typepadandthelegionofamillionblog platformstheyareallbetterthanwhatIofferhere.Thousands ofopensourcewebcontentmanagementsystems.Manyare greaterthanwhatwewilltalkabouthere.Andifyouwanttoflex yourmusclesandsaythatyoudiditthehardway,wellwrite yourengineinC(I'llevenadmireyouforwritingablogenginein plainPHP). So,itisnotthemostconvenientoreasiest,norisitthehardest. But,whatDjangooffersyouisLegoblocks,thechancetocraft somethingofyourownimagination,ablogenginemadeyour way,madebyyou,anditgivesyouallthesupportyouneed (documentationandcommunity). And,weallknow,thereisonlyonecoolscriptinglanguage, right?Python.Pythonhassoul.AndDjangoisdeeply Pythonic. So,doyouwanttogetcreative,doyouwanttobecoolwritea blogwithDjango(Iknowyouwantto).
IamnotsurethatIwrotethisforanyrealaudiencedoesanyonebut mewanttowriteablogengine,orisit,well,done boring?Perhaps. Igainedalotjustwritingit,andsothatisenoughtojustifymydoingit. Butitcertainlywouldthrillmetobitsifsomeonefindssome,ifnotall, ofthetutorialofsomeuse.Ifyoudid,whynotsendmeaTweet @sandcurves.

Sandcurves
Home AboutMe Topics Contact Blogroll

About
My nameis Vernon Ilivein

Whatisthisabout:Thisisaverysimpletutorialtotakeyou throughbuildingablogusingDjango.Itissimple,butit'snot short.Don'tletthelengthfoolyouintothinkingthatit'sdifficult, itisn't. Djangoismainlyaimedatsmallgroupsofdevelopers,butwith thistutorialyoushouldbeabletodoeveryaspectby

NamibiaI'mapassionate blogger,computer enthusiast,naturalistand fatherSandcurvesismy personalwebsiteandblog More

BloggingProject
MeaningfulBlogProject Linuxandopensourse

andc

e .com/blog_engine/page/in od c ion/

1/4

12/23/11

In od c ion

ourself.M , .

( , )

Tutorials
B E T

Whowillbenefitthemost:I I .S , I .Y ' , I . Y Y , :

KeepUp
S S E F

WriteOnSandcurves
GuestPost

P .I D I P M P .I , ' .Y , , P ( 2.6 ) .I L , . I not P .Y , , .I I P , . B , P , , .I . Y S 3.I P , .W ' S 3 .O , M SQL.D ' ,I' . I U 10.04.I L , ' .I ' U , , .T .I L , . W T .I ' , U ,I' .Y . H HTML CSS .I' , , .S , ' ! T ' , I E . I .I H .I I ( ) , .Y

Work
I B W .I N N , N .

Ads

Don23DTrailer
NowPla ingDon2Trailersin 3D.CatchItAllonYouTube!
outube.com/Don2

LatestBoll woodVideos
Sta UpdatedOnYour FavoriteVideoCheckYahoo ForFulllengthVideo's.
www. ahoo.com/video

andc

e .com/blog_engine/page/in od c ion/

2/4

12/23/11

In od c ion

someofwhatIsayusefulevenifyouhostelsewhere. I'mnotgoingtogettomuchintoworkingwithimages,but ifyouareworkingonwebsites,you'llsoonerorlaterwant someimageeditingcapability.ForsomereasonUbuntu 10.04hasstoppedincludinggimp.Ithinksomedecision makersfelloutofatreeandhittheirheadshardona rock.Getthegimpifyoudon'talreadyhaveit.Ifyou don'thaveit,simplytype"sudoaptgetinstallgimp"in Terminal,andwaitawhile.Don'tknowwhat'sterminal, we'llgettothat. Youneedawebbrowser.Actually,eventuallyyouwantat leastaccesstoafewtocheckthatthingslookrockingin mostpopularbrowsers.Forthetutorial,I'mgoingto assumeyouareusingFirefox Alittletime,patiencetoreadthetutorial,andcoffee[ Mmmm,letsbreakaminutetogetourselvesacup,shall we.]Ifyoudon'tdrinkcoffee well,ofcourseyoudrink coffee you'reaLinuxgeek. SomeAd icefo doing he o ial

Ifyouareexperienced,thisisprobablynotthetutorialforyou anyway.Youmaygetsomethingoutofit,butyouareprobably goingtofinditreallyslowandboring.Ifyouareatotalbeginner withthisstuff,Iadviseyoutofollowthetutorialtoatee,do e ac l whatIsay.Onceyouhavedonethewholething,then startdiggingintomoreoftheDjangodocumentation,gethelpon forumsandstarttoplayaroundwithit.Ifyouplayaroundto early,you'llgetlost,andprobablynotfinishthetutorial.Onthe flipside,ifyoudothewholetutorialandyouneverplayaround withit,you'llalsohavelostout.B ,if o an olea nho odo hi ,follo heen i e o ial,all he a h o gh.I usuallydotutorialslikethisinw3mbrowser,inEmacsifyou candoitinatextbrowser(inwhichitworksgreat)youshould simplytokeeptwitterandthelikequiet. Ifyouaresomewhereinthemiddleyouhaveagoodbitof Python,andyouhavealreadypickedattheDjango documentationandjustgetstuckhereandthereonexactlyhow togoaboutgettingablogworking,thisshouldbejustthetutorial foryou.Whenitseemsdifficult,itismostlikelythatyouare goingtofast,ornotconcentratingonthedetails.Lookatit clearly,andoccasionallygobackafewtimes. Whenwritingthetutorial,whichIdidinafewchunks,whatI woulddoiscreateablogonmycomputerfollowingalong,thenI justdeletethewholethinganddoitagain,overandover.Inso doing,Iknowthateverythingisworking,thoughIdidn'tputitup onaserver.Iamworkingonanothernonblogwebsitewith Django,andsocouldtestoutsomeofwhatIsaidwhileIworked onthatsite.IfyouaretryingtogetagoodgripofdoingDjango websites,Iadviseyoutodothesamebuildone,delete,buildit again,delete.Eachtimeyou'lldoitdifferent,eachtimeyou'll looksomethingnewup,orsimply'get'somethinginawayyou didn'tbefore. Ifyouareahotshot,andjustwanttohaveareadthroughtosee ifsometourguide/travelagentcanreallywritegoodDjango

andc

e .com/blog_engine/page/in od c ion/

3/4

12/23/11

In od c ion

apps,youaremostwelcome,andmostofall,please,please, please,sendme ourfeedback.Ihavesortofinventedthe logicsideofitformyself,andmaywellhavemissedonbest practices.SometimesImayjusthavebeenstupidasarock. Feelfreetopointthatout,Iwouldlikethistutorialtobeusefulto someone.IamawarethatIhaveattimesabandonedtheDRY principal,butIhave,especiallywiththeviews,donethatinthe hopethatithelpsnewbieslearneasiertryingtolearnfrom tutorialswheretheconstantdrivewastomakeitfollowtheDRY principaltoomuchmadeifhardforme,andIamsureother beginners,tolearn. Ifanybitofitdoesn'tmakesense,pleaseletmeknow.I'lltryto helpyouout. Enoughchitchat,let'sbuildourblog

Share | ReturnToContentsPage|NextPage
Copyright20102011VernonSwanepoel|Djangopowered|WrittenwithEmacsonDebian| HostedbyIntegrit Namibia|Subscribe

andc

e .com/blog_engine/page/in od c ion/

4/4

12/23/11

S ep 1: In all Django

NewHere? Subscribe|AboutMe|Twitter|Contact

Sandcurves
BloggingNuts&Bolts VernonSwanepoel'sBlog

Step1:InstallDjango
Openyourterminal(Applications>>Accessories>>Terminal). Whileyouarethere,justrightclickonitandclick "AddthislaunchertoPanel"becauseyouaregoing tobeusingitalot.YoushouldnowseethelittleTV lookingblackicononyourpanelbaratthetopof yourscreen. Ifyouarenewtoterminal,don'tworry,I'llhelpyoustepbystep. Whenyouopenit,youshouldseesomethinglikethis:

Sandcurves
vernon@slick:~$ withablinkingcursorinfront.Inthiscase'vernon'ismyname, andmyusername,and'slick'ismyimaginarycomputer's name. Thisiswellcoveredbythedocumentation,soIamnotgoingto getcarriedawayhere.Justrealquick. Openyourbrowser(Firefox,I'llassume)andgotothispage: http://www.djangoproject.com/download/IusuallysetFirefoxto downloadtomytmpdirectory.Ifyouarenottofamiliarwithhow thesethingswork,dothesame.InFirefox,clickon'Edit'.Go downtothelastoption,'preferences'andclickit.Alittlewindow opensup.Clickon'General'.WhereitshowsDownloads,click onthe'savefilesto'bit.Click'browse'togetthedirectory,and juststarttyping"/tmp".It'llautocompleteitforyou(justpress thetabkey)andpress'close'. Now,ontheDjangodownloadpage,lookforthisline: First,downloadDjango1.2.3.tar.gz.Then: Note,theversionmayhavechanged.Pressonitto download. NowopenyourTerminalandtype(withtherightversion number,ofcourse)allthefollowing:
Home AboutMe Topics Contact Blogroll

About
My nameis Vernon Ilivein

NamibiaI'mapassionate blogger,computer enthusiast,naturalistand fatherSandcurvesismy personalwebsiteandblog More

BloggingProject
MeaningfulBlogProject Linuxandopensourse

andc

e .com/blog_engine/page/ ep-1-in all-django/

1/2

12/23/11

S ep 1: In all Django

vernon@slick:~$cd/tmp/ vernon@slick:/tmp$tarxzvfDjango1.2.3.tar.gz vernon@slick:/tmp$cdDjango1.2.3 vernon@slick:/tmp/Django1.2.3$sudopython setup.pyinstall Okay,Idon'twanttogettoocarriedawaywithinstallingit.Ifyou havetroublewiththataspect,you'llfindlotsofhelpelsewhere.

Tutorials
BlogEngineTutorial

KeepUp
SubscribebyEmail SubscribebyFeed

Share | PreviousPage|ReturnToContentsPage|NextPage

WriteOnSandcurves
GuestPostonmyblog

Work
IworkatandBeyondasthe managerofourWindhoek office.Ifyouwanttoknow moreaboutNamibiaand theandbeyondoperations inNamibia,visitour Namibiapagesonthe website.

Ads

DjangoScalablePlatform
Eas deplo mentforDjango apps.P thon2.6andgit integration.
www.nuagehq.com

PhpApplicationDo nload
CodeandDebugYourApps OnTheFl InTheCloud. DownloadtheTrial
windowsa ure.com

Copyright20102011VernonSwanepoel|Djangopowered|WrittenwithEmacsonDebian| HostedbyIntegrit Namibia|Subscribe

andc

e .com/blog_engine/page/ ep-1-in all-django/

2/2

12/23/11

S ep 2: S a

P ojec

NewHere? Subscribe|AboutMe|Twitter|Contact

Sandcurves
BloggingNuts&Bolts VernonSwanepoel'sBlog

Step2:StartProject
Okay,readyfortheadventuretobegin?UnlikePHPorsimilar things,youcanjustputyourDjangoprojectanywhere.Ifyou havenoidea,andyouareonUbuntu(whichIwillassumefrom nowon),createafilecalled'project'inyourhomedirectory,like this: InyourTerminal,type'cd'togetgetbacktoyourhome directory. vernon@slick:/tmp$cd Now,letsmakeaproject vernon@slick:~$mkdirproject Now,letsgointothatdirectory:

Sandcurves
Home AboutMe Topics Contact Blogroll

About
vernon@slick:~$cdproject LetstestthatDjangoisonourpythonpath.Type'python'atthe prompt: vernon@slick:~$python Python2.6.5(r265:79063,Apr162010,13:09:56) [GCC4.4.3]onlinux2 Type"help","copyright","credits"or"license"for moreinformation. >>> Nowtype"importdjango" >>>importdjango >>>
My nameis Vernon Ilivein

NamibiaI'mapassionate blogger,computer enthusiast,naturalistand fatherSandcurvesismy personalwebsiteandblog More

BloggingProject
MeaningfulBlogProject Linuxandopensourse

andc

e .com/blog_engine/page/ ep-2- a -p ojec /

1/3

12/23/11

S ep 2: S a

P ojec

Youshouldseenothing.Ifyouseesomethinglikethis: >>>importdjango Traceback(mostrecentcalllast): File"",line1,in ImportError:Nomodulenameddjango >>> thenDjangoisn'tonyourpythonpath.Itprobablymeansthat youdidsomethingwrongwithyourinstallation.Gocarefully throughtheDjangodocumentationandtryagain. Okay,ifyouhaveDjangoupandrunning,thenext stepistoactuallycreateourproject.Inyour terminal,getoutofPythonbyholdingdown Controlandpressing'd'.FromhereonI'llsimply say'pressCtrld'andyou'llknowwhatImean. Okay,nowtype"djangoadmin.pystartprojectzing".I'mcallingit zing.Youcancallitbyyourname,oryourgirl/boyfriendorcat's name,or ephanoae _co ona .Anything.Iwouldkeepit short,it'llhelpyouwhenyouarerepeatedlytypingthatintoyour terminal. vernon@slick: /project$djangoadmin.py startprojectzing Thatcreatesadirectorycalled'zing'(orwhateveryounamed it).IfyouarenotfamiliarwiththeLinuxfilesystems,youhavea hierarchyofdirectories,startingfrom'/'asthebasedirectory, intoyour'/home/username'.Whenwecreated'project'that wouldbe'/home/username/project'andnowwiththedjango project'zing'thatwecreatedinsideofit,weget '/home/username/project/zing'.Inourterminalwearestillinthe 'project'directory.Letsgointothe'zing'directorywiththe'cd' commandagain: vernon@slick: /project$cdzing vernon@slick: /project/zing$ Now,let'sseewhatwemade.Toseewhatisinthedirectory, weusethecommand'ls': vernon@slick: /project/zing$ls __init__.pymanage.pysettings.pyurls.py vernon@slick: /project/zing$ Okay,ifyoujustwanttoseewhatisinafilewithoutactually goingintoit,youcanusethecommand'cat'.Don'tworryifyou don'tunderstandanything,orifitlooksscarry,justtype'cat'and

T o ial
BlogEngineTutorial

KeepUp
SubscribebyEmail SubscribebyFeed

W i eOnSandc
G e Po onmyblog

Wo k
IworkatandBeyondasthe managerofourWindhoek office.Ifyouwanttoknow moreaboutNamibiaand theandbeyondoperations inNamibia,visitour Namibiapagesonthe website.

Ad

ShellSc ip ingT o ial


India' Onl Comp e T ainingIn b Co po a e T aine .Regi e No
.ne o kn .ne

Logi icSol ion ?


Ai f eigh ,Seaf eigh ,Road andRailT an po &Ne Da Deli e !
.mablogi ic .com

andc

e .com/blog_engine/page/ ep-2- a -p ojec /

2/3

12/23/11

S ep 2: S a

P ojec

eachofthefilenames,'__init__.py''manage.py','catsettings.py', 'caturls.py' vernon@slick:~/project/zing$cat__init__.py vernon@slick:~/project/zing$catmanage.py #!/usr/bin/envpython fromdjango.core.managementimport execute_manager try: importsettings#Assumedtobeinthesame directory. exceptImportError: importsys sys.stderr.write("Error:Can'tfindthefile 'settings.py'inthedirectorycontaining%r.It appearsyou'vec .................andsoon..... Mmmm,strangethingthat__init__.pyfiledidn'tseemtohave anythinginit.ThatisaPythonthing.Eachdirectoryhasto haveoneofthoseemptyfilestomakePythontreatitasa pythonpackage. Asfortherest,we'llgettheresoon Patyourselfontheback,you'vecreatedaDjangoproject.It doesn'tdoanything,butthereitis,allshiny

Share | PreviousPage|ReturnToContentsPage|NextPage
Copyright20102011VernonSwanepoel|Djangopowered|WrittenwithEmacsonDebian| HostedbyIntegrit Namibia|Subscribe

andc

e .com/blog_engine/page/ ep-2- a -p ojec /

3/3

12/23/11

S ep 3: C ea e Ba e HTML Templa e

NewHere? Subscribe|AboutMe|Twitter|Contact

Sandcurves
BloggingNuts&Bolts VernonSwanepoel'sBlog

Step3:CreateBaseHTMLTemplate
Okay,hereIamgoingtodivergefromthenormalDjango tutorials,becauseIwantthistutorialtoincludeeverything,and thatmeansthatweneedtowritesomeHTMLaswell. I'mgoingtoassumealittlemorefamiliaritywithHTMLthanIdid withtheTerminal,butI'llstillmostlyspelleverythingout.Iwant tobesurethatalmostanyonereadingthistutorialwillbeableto buildablogforthemselves. Wecanstayinthe'zing'directoryfornow.Letsmakeanother directorywithinit,andcallit'template'. vernon@slick:~/project/zing$mkdirtemplate vernon@slick:~/project/zing$cdtemplate LetscreateourHTMLfile.Youcantypethisinanyplaintext editor,likeGeditorwhateveryouuse.Justmakesureitisnota wordprocessororawysiwygeditor.I'mgoingtouseEmacsas myexample. vernon@slick:~/project/zing/template$emacs base.html Thiswillopenyouremacsfile.ChangeEmacsforgeditor bluefishoranythingwhateveritisyouuse.Itmustjustbe somethingthatisonyoursystem.Ifyouarehappywithnanoor somethinglikethat,bemyguest.Ifyouhavenoidea,andyou areontheGnomeUbuntudesktop,juststickwithGedit. Typethefollowing: <doctypehtml> <html> <metacharset="UTF8"> <title>ZingBlog</title>

Sandcurves
Home AboutMe Topics Contact Blogroll

About
My nameis Vernon Ilivein

NamibiaI'mapassionate blogger,computer enthusiast,naturalistand fatherSandcurvesismy personalwebsiteandblog More

BloggingProject
MeaningfulBlogProject Linuxandopensourse

andc

e .com/blog_engine/page/ ep-3-c ea e-ba e-h ml- empla e/

1/4

12/23/11

Step 3: Create Base HTML Template

<link el="al e na e" pe="applica ion/ + ml" i le=" fo ing"h ef="####We'llcomeback o hi ####" <link el=" le hee " pe=" e /c " h ef="/media/c / le.c "> <link el="icon" pe="image/gif" h ef="/media/ ing.ico"> <me aname="de c ip ion"con en ="M onde f l blog"> <me aname=" obo "con en ="all"> </head> <bod > <!S a i le> <di id=" i le"> <h1>ZingBlog</h1> <h2>Theblog</h2> <!End i le> </di > <!S a con en > <di id="con en "> <!Endcon en > </di > <!S a ideba > <di id=" ideba "> <!End ideba > </di > <!S a foo e > <di id="foo e "> <!Endfoo e > </di > </bod > </h ml>

T o ial
BlogEngineT o ial

KeepUp
S b c ibeb Email S b c ibeb Feed

W i eOnSandc
G e Po onm blog

Wo k
I o ka andBe onda he manage ofo Windhoek office.If o an okno mo eabo Namibiaand heandbe ondope a ion inNamibia, i i o Namibiapage on he eb i e.

Ad

PhpApplicationDownload
CodeandDebugYourApps OnTheFl InTheCloud. DownloadtheTrial
windowsa ure.com

Ja peeGreenSportsCit
TheKove:2/3/4BHKApts, Delhi/NCRWithWorldClass AmenitiesViewNow!
www.Ja peegreensthekove.com

Sofa ,if o kno HTML, impleandno mal.Iincl ded ome of hecommonheade ff,j beca eIamaiming omake hi o iala comple ea po ible. No ,le add heDjango ff.The e empla e ag a egoing

sandcurves.com/blog_engine/page/step-3-create-base-html-template/

2/4

12/23/11

S ep 3: C ea e Ba e HTML Templa e

toturnyourHTMLfilefromanormaloneintoatemplate.Add thetextwritteninred. <doctypehtml> <html> <metacharset="UTF8"> <title>{%blocktitle% ZingBlog{%endblock % </title> <linkrel="alternate"type="application/rss+xml" title="rssforzing"href="####We'llcomebackto this####"> <linkrel="stylesheet"type="text/css" href="/media/css/style.css"> <linkrel="icon"type="image/gif" href="/media/zing.ico"> <metaname="description"content="Mywonderful blog"> <metaname="robots"content="all"> </head> <body> <!Starttitle> <divid="title"> <h1>ZingBlog</h1> <h2>{%blockunder_title% Theblog{%endblock % </h2> <!Endtitle> </div> <!Startcontent> <divid="content"> {%blockcontent% Herebeblogstuff{% endblock% <!Endcontent> </div> <!Startsidebar> <divid="sidebar"> <!Endsidebar> </div> <!Startfooter> <divid="footer">

andc

e .com/blog_engine/page/ ep-3-c ea e-ba e-h ml- empla e/

3/4

12/23/11

S ep 3: C ea e Ba e HTML Templa e

<p>Copyrightyour_name&copy2010</p> <!Endfooter> </div> </body> </html>

Okay,youdon'thavetogotoallthetroubletowriteitallout. Justcopyandpasteitfrommine.Butdotakethetimetohavea lookatitcarefullysothatyoucanseewhatisgoingon. Onceyouaredone,saveitandcloseyourtexteditor.

Share | PreviousPage|ReturnToContentsPage|NextPage
Copyright20102011VernonSwanepoel|Djangopowered|WrittenwithEmacsonDebian| HostedbyIntegrit Namibia|Subscribe

andc

e .com/blog_engine/page/ ep-3-c ea e-ba e-h ml- empla e/

4/4

12/23/11

S ep 4: C ea e CSS file

NewHere? Subscribe|AboutMe|Twitter|Contact

Sandcurves
BloggingNuts&Bolts VernonSwanepoel'sBlog

Step4:CreateCSSfile
WehavewrittenalotofHTMLstuff,right.Ourwebsitemustbe great.Takealook: vernon@slick:~/project/zing/template$firefox base.html Vernon,thatisn'tcool:

Zing Blog
%blockunder_title% The blog %endblock%
{%blockcontent%}Herebeblogstuff{% endblock%} Copyrightyour_name2010

Sandcurves
Home AboutMe Topics Contact Blogroll

About
My nameis Vernon Ilivein

NamibiaI'mapassionate blogger,computer enthusiast,naturalistand fatherSandcurvesismy personalwebsiteandblog More

Okay,andCSSisn'tgoingtosaveusyeteither,bearwithme. Wejustwanttoaddsomesimplecssforthetimebeing.When weuploadthesitewearegoingtochangethings,butfornow justaddtheCSStothefileitself. Openthebase.htmlfileinyourtexteditoragain"emacs

BloggingProject
MeaningfulBlogProject Linuxandopensourse

andc

e .com/blog_engine/page/ ep-4-c ea e-c

-file/

1/3

12/23/11

Step 4: Create CSS file

base.html" Justignorethisline: <linkrel="stylesheet"type="text/css"href="/media/css/style.css"> fornow.We'llgetbacktoit. Addthebitinredtoyoursite. <doctypehtml> <html> <metacharset="UTF8"> <title>{%blocktitle% ZingBlog{%endblock% </title> <linkrel="alternate"type="application/rss+xml" title="rssforzing"href="####We'llcomebackto this####" <linkrel="stylesheet"type="text/css" href="/media/css/style.css"> <linkrel="icon"type="image/gif" href="/media/zing.ico"> <metaname="description"content="Mywonderful blog"> <metaname="robots"content="all"> <styletype="text/css"> /*Page*/ body{padding:0margin:0fontfamily:Arial, Helvetica,Tahoma,sansserif /*Titlesection*/ #title{float:leftwidth:100%padding:0margin:0border:0border bottom:1pxsolid#cccccc #titleh1{padding:10px0050pxfont size:60ptmargin:0fontfamily:"MyriadPro",Arial, Helvetica,Tahoma,sansserif #titleh2{margin:0padding:0textalign:center /*Contentsection*/ #content{float:leftborder:0margin:0padding:10px 2%02%width:75% /*Sidebarsection*/ #sidebar{float:leftborder:0borderleft:1pxsolid #ccccccpadding10px2%0 2%width:20%margin:0 /*Footersection*/ #footer{float:leftborder:0bordertop:1pxsolid #ccccccpadding:0margin:0width:100%text align:center </style> </head> <body>

T o ial
BlogEngineTutorial

KeepUp
SubscribebyEmail SubscribebyFeed

W i eOnSandc
G e Po onmyblog

Wo k
IworkatandBeyondasthe managerofourWindhoek office.Ifyouwanttoknow moreaboutNamibiaand theandbeyondoperations inNamibia,visitour Namibiapagesonthe website.

Ad

F eeWeb i eFo B ine


Easil CreateAWebsiteIn15 Mins.FreeFromGoogleTo YourBusiness!
www.indiagetonline.in

Wan ToDe ignA Web i e?


DesignYourWebsiteB The BestWebDesignCompan In India.SeeMore

sandcurves.com/blog_engine/page/step-4-create-css-file/

2/3

12/23/11

S ep 4: C ea e CSS file

<!Starttitle> <divid="title"> <h1>ZingBlog</h1> <h2>{%blockunder_title%}Theblog{%endblock %}</h2> <!Endtitle> </div> <!Startcontent> <divid="content"> {%blockcontent%}Herebeblogstuff{% endblock%} <!Endcontent> </div> <!Startsidebar> <divid="sidebar"> <!Endsidebar> </div> <!Startfooter> <divid="footer"> <p>Copyrightyour_name&copy2010</p> <!Endfooter> </div> </body> </html>

Okay,that'snotveryfancy,butI'llleavetherestofthatupto you.Forthetutorial,justleaveitlikethatbeforeyouspend hourstryingtogetyoursitelookingjustrightLetsgetbackto Django

Share | PreviousPage|ReturnToContentsPage|NextPage
Copyright20102011VernonSwanepoel|Djangopowered|WrittenwithEmacsonDebian| HostedbyIntegrit Namibia|Subscribe

andc

e .com/blog_engine/page/ ep-4-c ea e-c

-file/

3/3

12/23/11

S ep 5: S a

Blogging app

NewHere? Subscribe|AboutMe|Twitter|Contact

Sandcurves
BloggingNuts&Bolts VernonSwanepoel'sBlog

Step5:StartBloggingapp
Closeyourtexteditorfornow,andgobacktoyourTerminal. IfyoustillhavethesiteopeninFirefox,andopeneditwith Terminal,justcloseit.Youdon'tevenneedtobookmarkit becausethenexttimewelookatthesitewearegoingtobe runningyourownserver(thanksDjango). Weleftoffinourtemplatedirectoryandwewanttogobackto the'zing'directorytocreateourapplication.Typethefollowing: vernon@slick:~/project/zing/template$cd../ Doubledots'..'refersinLinuxfilesystemtotheparent directory.Youcouldgetbackallthewaybychainingthem together"cd../../../"Anyway,letsgetbacktobuildingourblog. vernon@slick:~/project/zing$pythonmanage.py startappblog vernon@slick:~/project/zing$ls blog__init__.pycsettings.pytemplate __init__.pymanage.pysettings.pycurls.py IfyouarefamiliarwithPython,you'llknowthose.pycfilesare justcompiledversionofthenormal.pyfilesinPython.Each timeafileisrunforthefirsttime,Pythonmakesyouacompiled version(compiledbytecode).Type: vernon@slick:~/project/zing$catsettings.pyc See,crazystuffforyourcomputertoread.You'llgetusetoit, whenyoulookatyourpythondirectories,you'llsortoflookonly forthe.py. Moreimportantly,whenyouranthe'ls'command,yousawthe new'blog'directorysittingthere.Djangowaskindenoughto writesomestuffforyouintherealready.Havealookwiththis command:

Sandcurves
Home AboutMe Topics Contact Blogroll

About
My nameis Vernon Ilivein

NamibiaI'mapassionate blogger,computer enthusiast,naturalistand fatherSandcurvesismy personalwebsiteandblog More

BloggingProject
MeaningfulBlogProject Linuxandopensourse

andc

e .com/blog_engine/page/ ep-5- a -blogging-app/

1/2

12/23/11

S ep 5: S a

Blogging app

vernon@slick:~/project/zing$lsblog __init__.pymodels.pytests.pyviews.py Thereisanother'__init__.pyfilethatyouknowalready.Weare notgoingtotouchthetest.pyfile(youcandeleteififyoulike everythingneatandclean.You'llgettoknowtherestlater. Please,if oufeelalittleoverwhelmedatthispoint,don't giveup.Ifyougetstuck,pleasegivemesomefeedbackyou canjustsendmeatweetat@sandcurvesorcontactmethrough thecontactpage.

Tutorials
BlogEngineTutorial

KeepUp
SubscribebyEmail SubscribebyFeed

WriteOnSandcurves
Share | PreviousPage|ReturnToContentsPage|NextPage
GuestPostonmyblog

Work
IworkatandBeyondasthe managerofourWindhoek office.Ifyouwanttoknow moreaboutNamibiaand theandbeyondoperations inNamibia,visitour Namibiapagesonthe website.

Ads

Blogs
Blogsanddiscussionsledb businessintelligencegurus. Go!
www.AllAnal tics.com

Ja peeGreenSportsCit
TheKove:2/3/4BHKApts, Delhi/NCRWithWorldClass AmenitiesViewNow!
www.Ja peegreensthekove.com

Copyright20102011VernonSwanepoel|Djangopowered|WrittenwithEmacsonDebian| HostedbyIntegrit Namibia|Subscribe

andc

e .com/blog_engine/page/ ep-5- a -blogging-app/

2/2

12/23/11

S ep 6: Se Up Da aba e

NewHere? Subscribe|AboutMe|Twitter|Contact

Sandcurves
BloggingNuts&Bolts VernonSwanepoel'sBlog

Step6:SetUpDatabase
Lateronwe'lluseMySQLonyouractualhostserver,butfor development,we'llusesqlite3.Itshouldalreadybeonyour system,butmaybenotonyourfilepath.Typethefollowingin yourterminal: vernon@slick:~/project/zing$sqlite3 Youshouldseesomethinglikethis:

Sandcurves
SQLiteversion3.6.22 Enter".help"forinstructions EnterSQLstatementsterminatedwitha"" sqlite> Ifnothinghappens,letsjustfixthattheeasyway: vernon@slick:~/project/zing$sudoaptgetinstall sqlite3 Done,good. Now,ifyouwerescaredoffbythethoughtofthedatabase,don't be.AllwehavelefttodoistellDjangoaboutourdatabase,and we'lldothatwiththesettings.pyfile. YoucanopenthesettingsfilefromyourTerminalagain.From nowonI'lljustsayemacs,butyouknowthatyoucanuse whateveryourfavoritetexteditoris. vernon@slick:~/project/zing$emacssettings.py Atfirstglancethesettings.pyfilemightlookalittledaunting,but you'llsoongetusetoit.Wearegoingtodoafewthingsin here.Don'tbetoworriedaboutdoingthewrongthing.Ifitall goeswrongyoucanjustdeletetheentireprojectandstartfrom
NamibiaI'mapassionate blogger,computer enthusiast,naturalistand fatherSandcurvesismy personalwebsiteandblog More Home AboutMe Topics Contact Blogroll

About
My nameis Vernon Ilivein

BloggingProject
MeaningfulBlogProject Linuxandopensourse

andc

e .com/blog_engine/page/ ep-6- e -da aba e/

1/3

12/23/11

S ep 6: Se Up Da aba e

scratch. Fornow,letseditafewthings.Firstup,scrolldowntothis section: DATABASES={ 'default':{ 'ENGINE':'django.db.backends.',#Add 'postgresql_psycopg2','postgresql','mysql', 'sqlite3'or'oracle'. 'NAME':'',#Orpathtodatabasefileifusing sqlite3. 'USER':'',#Notusedwithsqlite3. 'PASSWORD':'',#Notusedwithsqlite3. 'HOST':'',#Settoemptystringforlocalhost. Notusedwithsqlite3. 'PORT':'',#Settoemptystringfordefault. Notusedwithsqlite3.

T o ial
BlogEngineTutorial

KeepUp
SubscribebyEmail SubscribebyFeed

W i eOnSandc
G e Po onmyblog

Wo k
IworkatandBeyondasthe managerofourWindhoek office.Ifyouwanttoknow moreaboutNamibiaand theandbeyondoperations inNamibia,visitour Namibiapagesonthe website.

Anythingaftera'#'inPythonisacomment.Readsomeofthat andyou'llseewhywestartwithsqlite3.Changeittothis: DATABASES={ 'default':{ 'ENGINE':'sqlite3', 'NAME':'zing.db', 'USER':'', 'PASSWORD':'', 'HOST':'', 'PORT':'',

Ad

MobilEngineOil
World'sFamousBrandForOil engineLearnHo WeAre BetterThanOthers
Mobil1.co.in

Thatshouldbereallyeasy.OncewestartworkingwithMySQL itisalittlemorecomplex.Youcaneitherdeleteorkeepthe comments.Itdoesn'treallymatter. Wespecifiedtwothings,thatweweregoingtousesqlite3and thename.Actually,inthecaseofsqlite3wealsospecifiedthe filepath,andfornowwearejustgoingtohaveitrighthere,in thezingdirectory. Whilewearehere,letsdosomethingelse.Letsaddour templatedirectory.Scrolldowntowhereitsays: TEMPLATE_DIRS=(andchangeitlikethis: TEMPLATE_DIRS=( '/home/username/project/zing/template' ) IfyouarenotfamiliarwithPython,itisreallyimportanttokeep thespaces.Keeptheindentationtofourspaces.Ifyoudon't understandwhatIamtalkingabout,almostanyintroductionto

DatabaseS stem
Businessintelligencee perts sharingtheirsecrets ith ou. Go!
.AllAnal tics.com

andc

e .com/blog_engine/page/ ep-6- e -da aba e/

2/3

12/23/11

S ep 6: Se Up Da aba e

Pythonwillclearthatupforyou. We'llbebackinthesettings.pyfilelateron,butfornowwejust wanttochangeonelastthing.IntheINSTALLED_APPS section(rightatthebottom),changeitlikethis(addthebitin red): INSTALLED_APPS=( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', #Uncommentthenextlinetoenabletheadmin: #'django.contrib.admin', 'zing.blog', ) ThisisaPythontuple,anditisagoodideatoputthatcommaat theend(incaseyouaddmore.) Wehavenowtoldourprojectwhichdatabasetouse,whereto findourHTMLtemplatesandwhichappswehavecreated. ClosethetexteditorandgobacktoyourTerminalagain.Do likeso: vernon@slick:~/project/zing$pythonmanage.py validate 0errorsfound Ifyougeterrors,youhavedonesomethingwrongabove.Look throughallthestepscarefully,andifyoucan'tfigureitout,one drasticoptionisjusttodeletethewholethingandstartagain. Youcandothisbygoingtotheprojectsdirectory,andtyping'rm r*'.Thenyou'llhavetostartfromthetopagain. Iamgoingtoassumealliswellandwecancarryon.

Share | PreviousPage|ReturnToContentsPage|NextPage
Copyright20102011VernonSwanepoel|Djangopowered|WrittenwithEmacsonDebian| HostedbyIntegrit Namibia|Subscribe

andc

e .com/blog_engine/page/ ep-6- e -da aba e/

3/3

12/23/11

S ep 7: W i e he Model

NewHere? Subscribe|AboutMe|Twitter|Contact

Sandcurves
BloggingNuts&Bolts VernonSwanepoel'sBlog

Step7:WritetheModel
Okay,nowwearegoingtoactuallycreateourdatabaseandput somethinginit.IfyouhaveevertriedtoworkwithPHPcreating websitesandusingdatabasecalls,thisisgoingtobelovely. I'mgoingtoassumeyouarecatchingontheterminalnow,and don'tneedeverythingdisplayed.InyourTerminal,type'cdblog' togetyourselfintoyourblogdirectory.Openyourmodels.pyfile inyourtexteditor.Leavethetopline,deletethecommentline, andaddtheredbelow: fromdjango.dbimportmodels fromdatetimeimportdatetime classCategory(models.Model): name=models.CharField(max_length=60) def__unicode__(self): returnself.name classTags(models.Model): name=models.CharField(max_length=60) def__unicode__(self): returnself.name classPost(models.Model): title=models.CharField(max_length=120) slug=models.SlugField(max_length=120, unique=True) description=models.TextField() body=models.TextField() published= models.DateTimeField(default=datetime.now) categories=models.ForeignKey(Category) tags=models.ManyToManyField(Tags) def__unicode__(self): returnself.title classMeta: ordering=['published'] Mmmm thatlookscomplicated.Actually,itis,butIamsure youcangetthefeelingforwhatwearedoingherereally quickly.Wehavethreeclasses,butthethirdone(classPost)

Sandcurves
Home AboutMe Topics Contact Blogroll

About
My nameis Vernon Ilivein

NamibiaI'mapassionate blogger,computer enthusiast,naturalistand fatherSandcurvesismy personalwebsiteandblog More

BloggingProject
MeaningfulBlogProject Linuxandopensourse

andc

e .com/blog_engine/page/ ep-7-

i e-model/

1/3

12/23/11

S ep 7: W i e he Model

shouldtellyoubasicallyeverythingwearedoinghereInour blogwewantatitle,abod ,thedateitwaspublished,tags andcategories.Soallthoselinesshouldmakesense. OnSandcurves.comIhaven'tworriedtomuchaboutgetting categoriesandtagsright,butforyou,I'mtryingtodoitright. Youcanlaterdecideexactlyhowtoimplementit,butIam goingtoassumeeachposthasonecategory,butcanhave severaltags.Hereismoreonthatlineofthinking:Tags& CategoriesdicussiononProblogger.net WeusedtwoTextFields,bodyanddescription.Thatisreally niceifyouwantalittleslugonamainpageandthewholepost onadetailpage.We'llgetbacktothatlater.Youmaynotlike todoitthatway,butIhavefounditsolvesthereallytrickystuff ofdoingthatsplittingwithPython.Fornow,doitmyway,follow alongandseehowitworks. Atthetopofthefile,thesecondline,weimported datetime.datetime.Thiswasneededtoimplementthepublished field. Theoneunusualthingistheslugfield,andit,likethebodyand descriptionfields,isalsotohelpusoutalittle.Theslugissimply aurlfriendlyversionofyourtitle,formakingtheurlofyourblog post.We'llgettothat. Theothertwoclasses(CategoriesandTags)aretheretodeal withrelationships,meaningthethingsinthosefieldsarenot uniquetooneblogpost,sowewantseparatetablesinour databaseforthem.Ifyouwanttounderstanditallbetter,havea lookatthispage: http://docs.djangoproject.com/en/dev/ref/models/fields/ Therestisquietselfexplanatory.Besureyougotthe indentationrightagain,itisimportant. Now,closethatfile,gobackintoyourTerminal,gobacktothe 'zing'directorywith'cd../'.Nowtypethisagain,justtomake surewedideverythingright: vernon@slick: /project/zing$pythonmanage.py validate 0errorsfound Ifyougoterrors,perhapslookattheindentationcarefully. Good,nowtypethis: vernon@slick: /project/zing$pythonmanage.py sqlallblog Ifallhasgonewell,yougetthiswonderfuldatabasedump output,innicecolors.Itlookslikeitdidalot,butactuallyitdidn't doanything.Itwasjustshowingyouthatall'swell.

Tutorials
BlogEngineTutorial

KeepUp
SubscribebyEmail SubscribebyFeed

WriteOnSandcurves
GuestPostonmyblog

Work
IworkatandBeyondasthe managerofourWindhoek office.Ifyouwanttoknow moreaboutNamibiaand theandbeyondoperations inNamibia,visitour Namibiapagesonthe website.

Ads

Ja peeGreenSportsCit
TheKove:2/3/4BHKApts, Delhi/NCRWithWorldClass AmenitiesViewNow!
www.Ja peegreensthekove.com

LatestBoll woodVideos
Sta UpdatedOnYour FavoriteVideoCheckYahoo ForFulllengthVideo's.
www. ahoo.com/video

andc

e .com/blog_engine/page/ ep-7-

i e-model/

2/3

12/23/11

S ep 7: W i e he Model

Toactuallystarttodostuff,type: vernon@slick:~/project/zing$pythonmanage.py syncdb I'mnotgoingtogointoittoomuchhere,buttheterm'syncdb' canbealittlemisleadingifyouarejuststartingoutwithit.Many changestoyourdatabasecan'tbemadewithit.Usethat commandtocreatenewtables,butwhenyouhavemistakes, you'llwanttoactuallygointothedatabaseshellandfixitthere. That'sabittomuchtogetintofornowwiththistutorial.For now,especiallywithsqlite3whileyouarejuststartingout(and havenovaluabledatainyourdatabase),youcanjustdeletethe databaseandrerun'pythonmanage.pysyncdb'. Okay,backtothejobathand.Whileyouranthat,itwasgoing toaskyouifyouwantedtocreateasuperuser.Theanswer,of course,isyes.I'msureyoucancomeupwithyourownnames. Whileyouareworkingonsqlite3,makethepasswordsimple. Andwriteitdown,you'llwanttorememberit.Iused'vernon'for myusernameand,fornow,'yup'formypassword.Do somethingsimilar. Ihopeyouadmiredallthatdatabasestuffitcreated.Ifyoutype 'ls'inTerminal,inthe'zing'directory,youwillseethenew databasefilesittingthere,'zing.db'.Ifyouarelikeme,you probablyalreadytriedtoseewhatisinit.'catzind.db'again givesyouameaninglessjumbleofstuff.Ifyoureallywantto havealook,type"sqlite3zing.db"andthentype'.table'When youwanttogetout,justtype'CtrlD'Djangogivesyouashell fordealingwithyourdatabaseaswell,(with'pythonmanage.py dbshell')I'msureyoucanfindoutmoreforyourselfwiththehelp ofGoogle.Letsmoveontomoreadventures.

Share | PreviousPage|ReturnToContentsPage|NextPage
Copyright20102011VernonSwanepoel|Djangopowered|WrittenwithEmacsonDebian| HostedbyIntegrit Namibia|Subscribe

andc

e .com/blog_engine/page/ ep-7-

i e-model/

3/3

12/23/11

S ep 8: W i e he Admin

NewHere? Subscribe|AboutMe|Twitter|Contact

Sandcurves
BloggingNuts&Bolts VernonSwanepoel'sBlog

Step8:WritetheAdmin
Ifyouwanttoblog,youneedabackendinterfacethatallows youtodothat.WithDjango,theadmininterfaceisincludedwith verylittlefuss. First,letscreateanadminfileintheblogapplicationtohandle our blog.IfyouareinTerminal,inyourzingdirectory,type'cd blog'togetyoubackintheblogdirectory.Now,type"emacs admin.py"tocreateandopenyouradmin.pyfile,thefilethatis goingtotellDjangowhatwewantforouradmininterfaceforthe blog. Now,inthatfile,typethefollowingcontent: fromdjango.contribimportadmin fromzing.blog.modelsimport* classPostAdmin(admin.ModelAdmin): filter_horizontal=('tags',) list_display=('title','published',) prepopulated_fields={'slug':('title',)} admin.site.register(Category) admin.site.register(Tags) admin.site.register(Post,PostAdmin) Trytohavealookthroughthatcodeaswellandunderstandit. Atthetop,inthesecondlineweimportedourblogmodelsthat wecreatedbefore(Tags,CategoryandPost).ThePostAdmin classwasjusttheretotellithowtorendersomeofthefields. Takenoteofthelastlineofthatclass.Wearetellingtheadmin sitetoprepopulatethe'slug'fieldwiththecontentsofthetitle field.Thisisverynice.Itmeansthatwhenyoutypeatitlefor theblog,itisgoingtojustfillintheslugfieldforyou. Thelastthreelinesshouldbeobvious,registeringeachsiteto beincludedwiththeadmininterface. Okay,acouplesmallthingslefttodo.First,gobacktothe'zing' directoryandopenupyoursettings.pyfileinyourtexteditor again.

Sandcurves
Home AboutMe Topics Contact Blogroll

About
My nameis Vernon Ilivein

NamibiaI'mapassionate blogger,computer enthusiast,naturalistand fatherSandcurvesismy personalwebsiteandblog More

BloggingProject
MeaningfulBlogProject Linuxandopensourse

andc

e .com/blog_engine/page/ ep-8-

i e-admin/

1/3

12/23/11

S ep 8: W i e he Admin

Now,scrollrighttothebottom,andlookatthelastfewlinesof theINSTALLED_APPSbit.Seethetwocommentedlines, deletethetopone,anduncommentthesecondlikethis: INSTALLED_APPS=( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.admin', 'zing.blog', ) Closethatfileandopenonewehaven'ttouchedsofar,the urls.py.First,beforewestarttochangeanything,readallthe contents. Okay,nowyoucanactuallyjustdeleteeverythingexceptthe linesthatIshowbelow: fromdjango.conf.urls.defaultsimport* fromdjango.contribimportadmin admin.autodiscover() urlpatterns=patterns('', (r'^admin/',include(admin.site.urls)), ) Theurlfileallowustomapagivenurltothecontentwewantit toputout.Thisisverydifferenttoanormalwebsite,butwe'll getintothatmorelater.Fornowjustsavethefile.Youcansee thatmostofwhatweleftbehindhastodowiththeadminsite. Now,weneedtoaddtheadminstufftothedatabase. Youcantype'pythonmanage.pyvalidate'againinyour Terminaljusttomakesurealliswell.Thenrun'python manage.pysyncdb'again. Now,openasecondterminal,andchangetothezingdirectory ('cdproject/zing'willgetyouthere).Onceinthe'zing'directory, type: vernon@slick: /project/zing$pythonmanage.py runserver Thiswasourfreeserver,includedwithDjango.Itisnotaheavy lifter,sodon'tuseittoserveyoursiteontheInternet.Butfor development,itisgreat. Nowforsomefun.OpenFirefoxagain,andenterthefollowing url:http://127.0.0.1:8000/

T o ial
BlogEngineTutorial

KeepUp
SubscribebyEmail SubscribebyFeed

W i eOnSandc
G e Po onmyblog

Wo k
IworkatandBeyondasthe managerofourWindhoek office.Ifyouwanttoknow moreaboutNamibiaand theandbeyondoperations inNamibia,visitour Namibiapagesonthe website.

Ad

Blogs
Getgreatideasandinsights frombusinessintelligence gurus.Go!
www.AllAnal tics.com

Ja peeGreenSportsCit
BiggestResidntialPlanned TownshipPresentsThe Kove,24BHK.BookNow!
www.Ja peegreensthekove.com

andc

e .com/blog_engine/page/ ep-8-

i e-admin/

2/3

12/23/11

S ep 8: W i e he Admin

Okay,yougetanerror?Ifitissaying"Pagenotfound"youare fine.Ifitissomeothererror,Djangogivesyouheapsofinfoin theretotrytofigureoutwhatyoudid. Assumingyougotthroughallthat,add'admin/'totheendofthe url,andthistimeyoushouldgetaloginscreen. Rememberthesuperuserwecreatedabove loginwiththat usernameandpassword.Yougetgreetedwiththisfantastic adminpage. Seethe'Blog'section wedidthat!Okay,nowclickon'Posts'. Whatdoyousee?"0posts"Ofcourse,wehaven'taddedany blogpostsyet. Intheupperrightandsideofthepage,clickon'addpost'.This isthepageyouaregoingtocometoeachtimeyouwantto createablogpost.Okay,bepatient,we'llbebackhereinno time. Closeitallup.Wehavebuiltthebackend,nowletsgetto writingtheactualblogapplogic.

Share | PreviousPage|ReturnToContentsPage|NextPage
Copyright20102011VernonSwanepoel|Djangopowered|WrittenwithEmacsonDebian| HostedbyIntegrit Namibia|Subscribe

andc

e .com/blog_engine/page/ ep-8-

i e-admin/

3/3

12/23/11

S ep 9: W i e he Vie

NewHere? Subscribe|AboutMe|Twitter|Contact

Sandcurves
BloggingNuts&Bolts VernonSwanepoel'sBlog

Step9:WritetheView
Idon'twanttogettomuchintoDjangobackgroundand philosophy(thereisplentyofinfoonthewebonwhatDjangois aboutalready).But,justalittleideawouldbeinorderhere. DjangoismorethanaCMS,itisawebframeworkandifyouare familiarwithMVC,Djangofollowsasimilaridea.Djangohas comeupwithit'sownwayofexpressingitMTV(Model, Template,View).Ifyouaren'tfamiliarwithCMSandMVC,look themup,thereisplentyofinfoontheweb.I'monlygoingtotalk aboutDjango'swayhere. TheideabehindthisMTVapproachisthatweworkwiththree aspectstocreateourwebsites.TheModelexpressesthe databaseside(asyousawwhenwecreatedthemodels.pyfile). TheTemplateistheHTML,CSSandeverythingneededto servethatup.Theplugbetweenthetwoistheview,which,in Django'swayofdoingthings,isthelogic. Toputitinreallysimpleterms,wehavestuffinourdatabase (models),wehavewaystoshowthestuff(templates)andwe havethelogicofwhatstufftoshowwhere(views). Good,that'sallI'llsayaboutthat.Youcanreadmore,just Googleit,orfollowthelinkIgaveabove.Butfornow,forget aboutit,andletsconcentrateoncreatingtheviewsforourblog. Ourviews.pyfileisintheblogapp,remember.Openitupina texteditor.Iamsureyouknowhowtodothatbynow.Youcan openupasecondTerminalatthispoint,tokeeponerunning ourdevelopmentserver. Bearwithmeontheviews,becauseIthinkitisthepartofthe applicationwhereyouneedtoreallyunderstandwhatyouare doing.Djangocomeswithgenericview,wherecommonlogicis bundledtogetherandyoudon'tneedtoprogramyourownview atall,andthisstuffisactuallygreatforblog,butfornow,letsget downanddirtyandwritethelogicoutourselves.Thereisalot ofadvantagetothis,ofcourse youcantwistyoursiteyour wayanddoreallyfunthings.You'llwanttoreallygetinto Pythonproperlyinordertotakefulladvantageofthecapability providedbytheviews.

Sandcurves
Home AboutMe Topics Contact Blogroll

About
My nameis Vernon Ilivein

NamibiaI'mapassionate blogger,computer enthusiast,naturalistand fatherSandcurvesismy personalwebsiteandblog More

BloggingProject
MeaningfulBlogProject Linuxandopensourse

andc

e .com/blog_engine/page/ ep-9-

i e- ie /

1/10

12/23/11

S ep 9: W i e he Vie

Djangogi e o lo of a ofdoing hing ,b in he ie eha ea pecialcla called ende _ o_ e pon e.Wecan o o logico in he ie ,andpa i on ing he ende _ o_ e pon eme hod.I i apa of hedjango. ho c package, hichp o ide , o g e ed, ho c .Soo fi epi oimpo ha in oo ie . f omdjango. ho c impo ende _ o_ e pon e

T o ial
BlogEngineT o ial

KeepUp
S b c ibeb Email S b c ibeb Feed

Ne , eneed he fff omo da aba e.Nona da aba e codeneeded.We'llj impo hemodel cla e andge on i hi .Wecandoa ildca d( i h'*')impo ,b emembe he e ePo ,Tag andCa ego . f omdjango. ho c impo ende _ o_ e pon e f om ing.blog.model impo * Wea egoing oimpo omo e hing ha e'llge back o la e , heH pRe pon eRedi ec andda e ime.The H pRe pon eRedi ec allo o edi ec page ,and o 'll ee h la e on.Theda e imei ef l hen ea e o king i h, o g e ed,da e . f omdjango. ho c impo ende _ o_ e pon e f om ing.blog.model impo * f omdjango.h pimpo H pRe pon eRedi ec Oka ,if o e eb ilding o o nbloga hi poin o ho ld pa e,pe hap ge a a f omacomp e and hink eall ha d abo ha o an o e e p,andho .D eam p he l pa e n ,andall hebi ofcon en ,and hen o konmaking p hon e e ha pb pa inginch nk ofcode ha o empla ecan ead.In hi ca e,ofco e, o don' kno ho odo ha , ole makeali of an ,and hen e'llgoabo c af ing hem. Oka ,fo hi blogapplica ion,he ei o li : 1. Wha :Ahomepage i h hela e 7po .Wh 7?I eall doe n' ma e .Fo hi blog ea e going i h7. Ho :h p:// i e_name/Thi i o homepage. Wha :Ade ailpage, he e ecan ie he hole po andaddcommen . Ho :h p:// i e_name/ ea /mon h/ l g/So e'll ha e he ea (fo n mbe ,like2010), hemon h ( on mbe ,like07)and hepo l g( emembe ha f omo model .p file?Thi i he e ea e going o ei . Wha :Apageli ingallmon h ofagi en ea . Ho :h p:// i e_name/ ea /Thi i going oli all hemon h of ha ea , hichcanbeclicked o ee all hepo on ha mon h Wha :Apageli ingallpo b mon h. Ho :h p:// i e_name/ ea /mon h/Thi i going

W i eOnSandc
G e Po onm blog

Wo k
I o ka andBe onda he manage ofo Windhoek office.If o an okno mo eabo Namibiaand heandbe ondope a ion inNamibia, i i o Namibiapage on he eb i e.

Ad

DjangoCloudHosting
Productionhostingwithpush buttondeplo ment
gondor.io

Ven ZendPackage
Webdevelopmentstartupkit. Savethousandsin developmentcost.
www.ven onsolution.com/

2.

3.

4.

andc

e .com/blog_engine/page/ ep-9-

i e- ie /

2/10

12/23/11

S ep 9: W i e he Vie

5.

6. 7.

8. 9.

oli all hemon h of ha ea , hichcanbe clicked o eeall hepo on ha mon h What:A chi epage ,goingbackaf e hefi pageinch nk of10(j fo a o nde n mbe ). Ho :h p:// i e_name/a chi e/n mbe /The n mbe efe on mbe eda chi epage .O homepage ho e en, oa chi epage1 (h p:// i e_name/a chi e/1/)i going o ho he po 8 o17.Weco ldd plica e(o p a pe manen edi ec .) What:Apageli ingall heca ego ie . Ho :h p:// i e_name/ca ego / What:Apageli ingall hepo pe ca ego . Ho :h p:// i e_name/ca ego /ca ego _name/ Ca ego _name efe ,ofco e, o henameof heca ego . What:Apageli ingall he ag . Ho :h p:// i e_name/ ag /Apageli ingall he ag What:Apageli ingall hepo agged i ha pecific ag. Ho :h p:// i e_name/ ag / ag_name/The ag_namei henameof he ag.Apage ha li all hepo fo ha ag.

Weal o an a ideba , hich e'll'incl de' hich illha e na iga ion,RSSfeed,ali ofca ego ie andali of ag .Thi doe n' affec ha ep ino ie ,b i illbe hemain a ha omeof ho epage a elinked o. No e ha hemon hand ea pa e n mean ha if omeone chop off he la heend, he ge ano he ef lpage.We don' ac all an oc ea ealink o he ea page(I ' no m ch e),b e an a i e ha ha in elligen l inplace, andhen ean URL ha i c ho ho ldbe o h ome hing andcon ib e oo eb i e. Oka ,le ' b ild heco ef nc ionali .Wedon' b ild he l in he ie ,b Ifindi i a eall good a o hinkabo i .So le j p hemina commen .We'llp hea chi e and hehomepageinonef nc ion,beca e he a edoing he ame hing.Yo 'll oon ee ha Imean.Wea eno eall follo ing heDRYp incipal(don' epea o elf),b mo of o epea ingi eall imple ff,andi help nde and e ac l ha ea eb ilding.Yo a emo e han elcome o combine hef nc ion af e o d ,a o eefi . f omdjango. ho c impo ende _ o_ e pon e f om ing.blog.model impo * #h p:// i e_name/and h p:// i e_name/a chi e /n mbe / #h p:// i e_name/ ea /mon h/ l g/ #h p:// i e_name/ ea /mon h #h p:// i e_name/ ea / #h p:// i e_name/ca ego #h p:// i e_name/ca ego /ca ego _name #h p:// i e_name/ ag/ ag_name

andc

e .com/blog_engine/page/ ep-9-

i e- ie /

3/10

12/23/11

S ep 9: W i e he Vie

#http://site_name/tag/

Noweneedtobuildafunctionaroundeachofthose,thatgets therequest(whichcomesfromtheuser'sbrowsersayinggive methepage.Soourfirstlineisafunctioncall,withone arguement,therequestobject.Don'tworryifyoudon't understand,justfollowalong.Itshouldallbecomemoreclear aswemovealong. Weneedtoserveapageandhaveawaytostickstuffinit,and ourrender_to_responsegivesusonequick,easywaytodojust that. So,letsfilloutourviews.pymuchmore.Thisisstartingtolook likealot,buttrustme,itisn'thardtounderstandsofar.Weare justdoingalotofthesamething.Whenyoubecomemore proficientatit,you'llcombinealotofthese,butIwanttospellit allout. fromdjango.shortcutsimportrender_to_response fromzing.blog.modelsimport* deflist(request): #http://site_name/and http://site_name/archives/number/ returnrender_to_response('base.html',{ ,) defdetail(request): #http://site_name/year/month/slug/ returnrender_to_response('base.html',{ ,) defmonth(request): #http://site_name/year/month returnrender_to_response('base.html',{ ,) defyear(request): #http://site_name/year/ returnrender_to_response('base.html',{ ,) defcategory(request): #http://site_name/category returnrender_to_response('base.html',{ ,) defone_category(request): #http://site_name/category/category_name/ returnrender_to_response('base.html',{ ,) defone_tag(request): #http://site_name/tag/tag_name/ returnrender_to_response('base.html',{ ,) deftag(request): #http://site_name/tag/ returnrender_to_response('base.html',{ ,)

andc

e .com/blog_engine/page/ ep-9-

i e- ie /

4/10

12/23/11

S ep 9: W i e he Vie

Okay,tomakeitmorereadable,wearegoingtobreakitupa bit.I'llbuildeachfunctionbyitselffirst. Notethatwehaveanhtmlfileinthereturnvalueofthefunction. Ihavejustputin"base.html"butactuallywearegoingtochange thatyou'llsee. Letsfirstdothelistpage.Sowewant7itemsonthispageand alinktothenextlotinthearchives,andapreviouslinkwhenwe gofurtherdownthearchive.Doesthatmakesense?Ifyou don'tunderstandwhatIamdoing,Ithinkjustfollowingalongat thispointwillsoonclearitallup. Wearegoingtoneedtoimportoneotherthingonthispage,the archivepagenumber.Becauseourfirstpagedoesn'thavea numberwecanuseoneofthewonderfullittletricksofPython, giveadefaultvalue.I'llbuildthisfirstfunctionandthenexplain.

deflist(request,archive=1): #http://site_name/and http://site_name/archives/number/ page=(int(archive)*7) ifPost.objects.all().count()>page+7: posts=Post.objects.order_by('published') [page7:page] else: posts=Post.objects.order_by('published') [page7:] #nextandpreviousarchivepages ifPost.objects.all().count()>page next=(int(archive))+1 else: next=0 previous=(int(archive))1 returnrender_to_response('base.html', {'posts':posts, 'next':next, 'previous':previous, ,)

Inthefunctiondeclarationatthetop,weassignavalueto archiveasadefaultvalue.Iftheurlcontains /archive/some_number/thenthenumberwillbepassedto archive(we'llgettohowexactlythathappenswhenwetalk abouttheurlconfiglateron). Thenextthingisthepagevariable,wherewearecreatinga variablethatisgoingtogiveuschunksofseven.So,ifwegoto archivepage3,wearegoingtobelookingatposts22onwards, andsoon. Ifyouhaveanyfamiliaritywithprogrammingatall,you'llknow abouttypes(ints,strings,floatsandsoon).Wehavetochange thevalueofthearchivevariabletoanint(typecoercion).Thisis

andc

e .com/blog_engine/page/ ep-9-

i e- ie /

5/10

12/23/11

S ep 9: W i e he Vie

T S , R .

. .

.T . M . .W . , P .N .E , ? +7: ] . ' , .I , ' , .' '. P 7 . , , ' , . _ (' ')[

P . I ' _ ' I I I

.I

' , I

. ,

.J

' ,

, ( P " "). .W ' , .

A '

' .S , , ' .W .F ' ' ' , ' . _ / /1/, . 1, ' .H .I

W ' .

( , =1): # :// _ / :// _ / / / =="1": H R R ("/") =( ( )*7) P . . (). ()> +7: =P . . _ ('

')

andc

e .com/blog_engine/page/ ep-9-

i e- ie /

6/10

12/23/11

S ep 9: W i e he Vie

[page7:page] else: posts=Post.objects.order_by('published') [page7:] #nextandpreviousarchivepages ifPost.objects.all().count()>page next=(int(archive))+1 else: next=0 previous=(int(archive))1 returnrender_to_response('base.html', {'posts':posts, 'next':next, 'previous':previous, ,)

Assimpleasthat.Wetestedforastring(thatiswhytheone wasinquotes)toseeifitcamelikethatfromtheurl. Alright,thenextstopisourdetailpage.Thisistheonewhere weactuallyshowthesingleblogpost.

defdetail(request,sl): #http://site_name/year/month/slug/ try: post=Post.objects.filter(slug=sl)[0] try: previous_post= post.get_previous_by_published() except: previous_post="" try: next_post=post.get_next_by_published() except: next_post="" except: next_post="" previous_post="" post="" returnrender_to_response('base.html', {'post':post, 'next_post':next_post, 'previous_post':previous_post, ,)

Asyoucansee,gettingthepostvalueissosimple.You'llsee weputa'[]'attheend.Thisallowsustoreturnonevalue, ratherthanawholequeryset,sowecancallitdirectlyfromthe variable,nothavingtoiterateoverit.

andc

e .com/blog_engine/page/ ep-9-

i e- ie /

7/10

12/23/11

S ep 9: W i e he Vie

Themoredifficultstuff(well,itisn'tdifficult)isgettingthe previousandnextposts.Djangomakesthissupereasyforus byprovidingas'get_next_by'functionthatwecanuseto determinethenextandpreviousposts. Again,whenwerunout,weassignNullvaluestoavoiderrors. YoucanseethatIbuildthewholethingwitherrorhandling(the try/except).Asyouknow,wedon'twanttobreakourwebsite becauseofstupidcodingissues. Thewaythatwederivedthepostforthisurljustignorestheyear andthedate.Thatmeansthatifsomeoneentersthewrong year,butgetstheslugright,theywillstillseetherightblogpost. Tochangethatyouwouldneedtopassinmoreparameters fromtheurl,andfiltertheresultsfurther.I'mnotgoingtoworry aboutthathere.Youshouldbeabletodothatyourselfwithout anyissuebythetimeyouhavefinishedthistutorial. Thenextoneisasimpleone,gettingthepostsforagiven month.

defmonth(request,year,month): #http://site_name/year/month/ date=datetime.datetime(int(year),int(month), 1) try: posts=Post.objects.order_by(' published').filter(published__year=year).filter(published__month=month) except: posts="" returnrender_to_response('base.html', {'posts':posts, 'date':date, ,)

Ofcourseyouneedtheyearintheequationaswellforfinding themonththegivenmonthisrepeatedeachyear,sowefilter bothforyearandformonth. Youcankeepworkingthatsectionalot.Youcantestifthere aremonthsthatarewrittenwrong,ifthedatesgivenareinthe futureandsoon.Andthenreturndifferenterrormessagesfor them(you'llseewhenwegettotemplates).Fornow,let'sjust keepitsimple. Justtohelpusmakenicetitletags(waittillyouareinthe templates),we'llalsopassinadatevalue.Weneedtogive datetime.datetimeayear,amonthandaday.Wedon'thave,or care,abouttheday(wedon'tneedtoderiveitinourtemplates), sowe'lljustmakeitthefirstofwhatevermonthwehave,hence the1. Now,chopoffthemonthandlet'sworkwiththeyear.

andc

e .com/blog_engine/page/ ep-9-

i e- ie /

8/10

12/23/11

S ep 9: W i e he Vie

defyear(request,year): #http://site_name/year/ post_error="" year=int(year) yr=datetime.datetime(year,1,1)months= 12 by_month=[] if Post.objects.filter(published__year=year).count(): ifyear==datetime.datetime.now().year: months=datetime.datetime.now().month formonthinrange(1,months+1): by_month.append({datetime.datetime(year, month,1): Post.objects.filter(published__month=month).filter(published__year=year) ) elifyear>datetime.datetime.now().year: post_error="Itisnotyet%d,tryanearlier year."%year else: post_error="Therearenopostsfor%d."% year returnrender_to_response('base.html', {'by_month':by_month, 'yr':yr, 'post_error':post_error, ,)

Undertheyearwewanttoshowhowmanypoststherearein eachmonthofthatyear.Thisiseasyformostyears.The challangeisthecurrentyear,becausewedon'tjustwantto showresultsformonthsthatareinthefuture. So,iftheyearisthecurrentyear,wefindoutthemonth,then usethatasthevaluetoiteratethroughtherestofthemonths. Otherwisewejustdo12monthsniceandeasy. The'yr'valueisjustthrownintheresothatwehaveitforthe templatesaswell.Thatwaywehaveawaytoknowwhichyear wearetalkingabout.You'llunderstanditbetterwhenweget there. Nextupisthecategorypage.Aswedidabove,wehavetwo separateviewstowrite.Wecouldeasilycombinethem,butI prefertokeepthemseparatefornow. Sothefirstoneisjustthelistofcategories.Thingsaregetting easynow.

defcategory(request): #http://site_name/category/ returnrender_to_response('base.html',{

andc

e .com/blog_engine/page/ ep-9-

i e- ie /

9/10

12/23/11

S ep 9: W i e he Vie

'categories':Category.objects.all(),},)

Theonlynewthingtherewasthatwecalledadifferentclassin ourmodel,Category.Otherwise,itisjusttoeasy. So,thenextthingistogivepostsbyindividualcategories.

defone_category(request,category): #http://site_name/category/category_name/ posts=Post.objects.order_by(' published').filter(categories__name=category.lower()) returnrender_to_response('base.html', {'posts':posts, 'category':category, },)

Thisoneisagainreallysimple,butintroducessomethingnew. Doyounoticethe'categories__name'.Thisisbecausethe categoriesvalueinourmodels.pyfileisintheCategoryclass. Thedoubleunderscoresays"Getmethenameofthe category".InthiscasethereisonlyonethingintheCategory classname,butifthereweremore,youwouldstillworkwithit thesameway. Wealsopassavaluestraightfromthefunctiontothereturn thenameofthecategory.Wedothissothatinourtemplatewe cansaysomethinglike"Underxcategorywegottheseposts". AnotherthingIdidherewastomakesurethatwhatIpassedas avaluewaslowercase.Itisagoodideatoenterallnamesand thingslikethataslowercase,andthenyoucanjustmakethem capitalizedorwhateveryouneedinyoursite.But,justincase someonecapitalizeditintheurl,we'llsolvetheirproblemand makeitlowercase. Thelasttwo,thetags,wewilldobasicallyexactlythesamething overagain,onlythistimediggingintheTagsclass. I'mgoingtoassumethatyoucanmanagethatonyourown. DoingitonownalsomeansthatyouneedtoreadwhatIwrote aboveandunderstandit.

Share | PreviousPage|ReturnToContentsPage|NextPage
Copyright20102011VernonSwanepoel|Djangopowered|WrittenwithEmacsonDebian| HostedbyIntegrit Namibia|Subscribe

andc

e .com/blog_engine/page/ ep-9-

i e- ie /

10/10

12/23/11

S ep 10: S b- empla e

NewHere? Subscribe|AboutMe|Twitter|Contact

Sandcurves
BloggingNuts&Bolts VernonSwanepoel'sBlog

Step10:Subtemplates
Wehavesofarbeenadding'base.html'toeachofthereturn values,butactuallythatpageisabitstupidanddoesn'tknow whattodowithallwearethrowingatit. Wearegoingtomakenicelittleextensionstothat. Inyourterminal,gointothetemplatesdirectoryandcreatea newdirectorycalled'blog'. Now,onceagainIamgoingtodothisthelongway.Weare goingtocreateasmallfileforeachoftheurlpiecesthatwe createdtheviewfunctionsfor. Letsgoinorder.Inordertomakeiteasytoworkwith,name themthesamethingasyourviewfunctions.Theonlydifference isthatyoushouldputa.htmlendingtoeachone.Actually,you don'tevenneedtodothat,butitishelpfultotellyouwhatkindof fileyouaremaking. Thefirstonewewillcreateislist.html. Openupyourlist.htmlinyourtexteditor.Justasaplugfor Emacs,IfindthatthebestwaytowritemyDjangoappsisto actuallyopenupthetemplate,theview,andtheurls.py(which we'llgettosoon)allatthesametimeinsplitwindows.This makesitsomucheasiertocarryonthelogicthrough. Anyway,backtowork: {%extends'base.html'%} Thissimplefirstlineiswhatwewilluseineachofoursub templates.Iguessitsaysexactlywhatitdoes. Now,asidefromthatline,mostotherthingshavetobebetween blocktagstomakeitdoanythingofvalue. {%extends'base.html'%} {%blocktitle%}
NamibiaI'mapassionate blogger,computer enthusiast,naturalistand fatherSandcurvesismy personalwebsiteandblog More

Sandcurves
Home AboutMe Topics Contact Blogroll

About
My nameis Vernon Ilivein

BloggingProject
MeaningfulBlogProject Linuxandopensourse

andc

e .com/blog_engine/page/ ep-10-

b- empla e /

1/11

12/23/11

S ep 10: S b- empla e

%endblock% %blockcontent% %endblockcontent% Ifyourememberonour'base.html'fileweputinsometagsfor blocks.Wehadatitleblock,aunder_titleblockandacontent block.Simpleenoughyoucreatetheblocktagsinyourbase templateandthenyoucanwriteothertemplatesthatslotinto thoseblocks. Ifyouwantedtogetreallyfancy,youcannextthem,sothatyou havesubsubtemplatesfillingblocksinyoursubtemplates. Yougetthepicture. Whenyoulookattheexample,you'llseethatIwrotethe endblocksdifferently.ForthetitleIjustwrote %endblock% butforthecontentIaddedthe'content'totheendofit.That 'content'isonlythereforyourbenefitonceyourtemplatesget longandhavelotsofcontent,youwillstarttofinditdifficultto rememberwhatstartsandendswhere.Therearealso commentswiththetemplates %comment% (thereismoreon thatintheDjangodocumentation). I'mnotgoingtofillinthe'under_title'sectionI'llleavethatupto yourcreativity.Itisjusttheresothatyoucanhaveasub headingforthepage,undertheblogsname,togivesome indicationofwhatthepageisabout.Bythetimeyouhavethe restofthisstuffdown,thatisgoingtobereallyeasy. Okay,let'sjustdoitallinoneshotitisrathereasyonceyou getthehangofit. %extends'base.html'% %blocktitle% %ifprevious% Archive previous %else% ZingBlog %endif% %endblock% %blockcontent% %forpostinposts% <ahref="/ post.published.year / post.published.month / post.slug /"title=" post.title "> post.title </a> post.description safe <hr> %endfor%

T o ial
BlogEngineTutorial

KeepUp
SubscribebyEmail SubscribebyFeed

W i eOnSandc
G e Po onmyblog

Wo k
IworkatandBeyondasthe managerofourWindhoek office.Ifyouwanttoknow moreaboutNamibiaand theandbeyondoperations inNamibia,visitour Namibiapagesonthe website.

Ad

Blog
Visitthee pertcommunit for datamanagementand businessanal tics.
.AllAnal tics.com

DjangoClo dHo ing


Productionhosting ithpush buttondeplo ment
gondor.io

andc

e .com/blog_engine/page/ ep-10-

b- empla e /

2/11

12/23/11

S ep 10: S b- empla e

%ifprevious% <ahref="/archive/ previous /">&laquoPrevious</a> %endif% %ifnextandprevious% &nbsp &nbsp %endif% %ifnext% <ahref="/archive/ next /">Next</a> %endif% %endblockcontent% Scared?Don'tbe.Ifyouunderstandsomeprogramminglogic, thisisjustawaytoaddsomelogicintoourtemplates. Letsstartatthebottomandworkourwayup.Ifyoucansee boththeviews.pyfileandthelist.htmlfileatthesametime,you aregoingtounderstandsomuchfaster. Ifyoulookatthelastsection,lookforthelinewhereitsays %if previous% andletsstartfromthere.Iamnotgoingtogiveyou afulllectureonDjangotemplatetags,butjusttheonesweare using.Thereispleantyofdocumentationthatcanhelpyouout. But,rathersimplyput,thelogicisusuallyintagswithat persentagesign"%"insidethe" ".You'llseeweuseif statements: %ifsomething_or_other% andforstatements: %foriinsome_iterable% Withtheifstatementswecanusean"else"aswell.Witheach ofthem,aswedidwithblock,wehavetoclosethem: %ifprevious% Dothis %endif% Now,inthelist.htmlfile,wherewearedealingwiththelast sectioncamefromthepreviousandnextvaluespassedfromthe viewsfile.Ifyouhavealookagainattheviews.pyfile,inthe function"list"you'llseethereturnvaluehad"next":nextand "previous":previous. Itisthesevariablesthatwearetestingfornow.Wedon'tneed tosay'ifpreviousisnotNull',justlikeinPython,simplysayingif andthevariableisenough. So,ifthereisapreviouspage,thenwewilldisplaythelinktothe previouspageandifthereisanextpage,we'lldisplayalinkto it. Justforkicks,betweenthe'previous'and'next'Iputanotherif statement.Thisonechecksiftherearebothpreviousandnext pages,we'llseparatethetwohyperlinkswithspacesandapipe

andc

e .com/blog_engine/page/ ep-10-

b- empla e /

3/11

12/23/11

S ep 10: S b- empla e

symbol" ". Okay,thatwasratheralotofworktodosimplestuff,butitissort ofstandardnavigationinablog. Letsskiptheotherstuffinthe'content'blockfirstandgoupto the'title'block.Wetestedagain(usinganifstatement)for 'previous'.Why?Well,weknowthatifthevalueof'previous'is Null,weareonthehomepage.SoweusethistofilltheHTML titletags.Whenweareonthehomepage,itwillsay"ZingBlog" inourtabtitle,butwhenwegotothefirstarchivepage,itwillbe "Archive1". Areyougettingthehangofthis?Okay,letstacklethemainblog postbit. Ah,a'for'loop.Hownice. Wepassedthe'posts'valuetothetemplate.Itisiterableinthe templateandwecansearchforeachspecificblogpost.So 'postforposts'meansthatoneachloopthe'post'variablegets another'posts'object,fromwhichwecangetthetitle,body, publishedandsoon. Ifyoudon'tknowwhatIamtalkingabout,rememberthe models.pyfileandlookwhatwedidintheviews.pyfiletopass thevaluetothetemplates.Andthen,don'tworry,justfollow along. Nextweneedtocreateaurl. %forpostinposts% <ahref="/ post.published.year / post.published.month / post.slug /"title=" post.title "> post.title </a> Whatamess.Iknow,we'llfixit,butmakesureyouunderstand whatitisdoing. Topassavariabletothetemplate,weusethedoublecurly braces" ".Nowyoucanstartseeingsomeofthepowerofthe templates.Wearediggingrightintothe'post'object,togetat itsguts.'post.published'wouldgiveustheentirevalueforwhen itwaspublished,andwecouldusethatifwewantedto,butwe needayearandamonthfortheurl. Well,allwehavetodoisaskandDjangogiveth. 'post.published.year'givesusthestring2010ifyoupublished thisyear(atthetimeofwriting). The'post.slug'givesustheslug,thebitDjangosokindlydidfor ususingthetitlewecreatedintheadmin. Okay,ifyouknowabitofHTMLthenyouunderstandwhatwe didwiththerestofit.Wecreatedthisfat,wackinggreat hyperlinkforthestaticpageofthatblogpost.

andc

e .com/blog_engine/page/ ep-10-

b- empla e /

4/11

12/23/11

S ep 10: S b- empla e

W U '

'

. I

' .I . '

'

.T

, ' . ' '.T .I & HTML ,I .D ' , ' ') . B ,I D , HTML J S ' ' HTML.E O G A , ' ' ' ,

' '

, HTML < > ?& I I (

'

< > .B '

. ( . .

HTML, , .W ' . . ' .

C = __ T ( = __

.C __(

.M F ):

):

=60)

.M ): .C F ( __( ):

=60)

P ( .M ): = .C F ( _ =120) = .S F ( _ =120, =T ) = .T F () = .T F () = .D T F ( = . ) = .F K (C ) = .M T M F (T ) __ __( ): . M :

andc

e .com/blog_engine/page/ ep-10-

b- empla e /

5/11

12/23/11

S ep 10: S b- empla e

ordering=['published'] defget_absolute_url(self): return"/%s/%s/%s"%(self.published.year, self.published.month,self.slug) YoushouldknowenoughPythontoknowhowtopassvalues intoastring.Itshouldberatherclearwhatwearedoinghere withoutmeexplainingittomuch,wemadetheurl,completewith year,monthandtheslug. Nowclosethatfileandgobacktothe'list.html'template. Changethathorridurltoamuchsimplerone,asshownbelow: %forpostinposts% <ahref=" post.get_absolute_url "title=" post.title "> post.title </a> Sweet! Okay,don'tforgettheblockthatwedidn'tadd,the'under_title' block. ThelastthingIwantyoutodonowistogobacktoyour 'views.py'fileandchangethefiletowhichthe render_to_responseispointing.Lookunderthefunctionlist, andgodowntothereturnvalue.Whereitsays'base.html' changeitto'blog/list.html'becausethelist.htmlfileisinthe'blog' directoryofthetemplates.Gotthat? Movingon,afterlist,whatisthenexttemplatethatwearegoing toconcernourselveswith?'detail.html'Right.Sogobackinto yourtemplate/blogdirectorywhereyoucreatedthelist.htmland makeanewonecalled'detail.html'.Thisiswhatwearegoingto usetoshowourmainblogpost. Wecanstartoutjustthesameaswedidwith'list.html'inthatwe aregoingtoextendthesametemplate('base.html')andweare goingtofillthesameblocks('title'and'content'here,andagain, I'llleave'under_title'toyou). Aswegetintothis,theygeteasierandeasier,soletsjustjump rightinandwritethewholethingout. %extends'base.html'% %blocktitle% %post.title% %endblock% %blockcontent% <h3> post.title </h3> <p>Postedon post.published date:"Fj,Y" <p> post.description safe <br> post.body safe

andc

e .com/blog_engine/page/ ep-10-

b- empla e /

6/11

12/23/11

S ep 10: S b- empla e

<br> {%ifprevious_post%} <ahref="{{previous_post.get_absolute_url}}" title="{{previous_post.title}}"> &laquo&nbspPreviousPost:&nbsp&nbsp{{ previous_post.title}} </a> {%ifprevious_postandnext_post %}&nbsp|&nbsp{%endif%} {%ifnext_post%} <ahref="{{next_post.get_absolute_url}}"title="{{ next_post.get_absolute_url}}"> NextPost:&nbsp&nbsp{{next_post.title }}&nbsp&raquo </a> {%endif%} {%endblockcontent%} Ifyouhadfollowedalongonthepreviousexample(whenwedid 'list.html')thenthisoneshouldbeapieceofcake.Theuseof thedatewasnew.Again,thatisn'tsomethingthatIwill elaborateon,thisisoneexampleofhowyoucanusethedate templateoutputthatDjangogivesyou.Therearelotsofother options,justsearchthroughthedocumentation.Asastarting point,lookatthenowinDjangobuiltins. YoucanseethatIdidn'tmakemuchfusswiththe 'post.description'and'post.body'because,asIsaidearlier,ifI amwritingposts,IwantthefreedomtoaddmyownHTML. Also,thestylingforthesewillbetakencareofbythepageCSS, butthinkofdescriptionandbodyasbeingoneonthispage. Youcouldputthemina<div>tagifyouwantedto,andusea classtostylebetter.Thatisalluptoyou.Movingalong Nextwe'lldomonth. {%extends'base.html'%} {%blocktitle%}Postsin{{date|date:"M,Y"}}{% endblock%} {%blockcontent%} {%ifposts%} <ul> {%forpostinposts%} <li> <ahref="{{post.get_absolute_url}}"title="{{ post.title}}"> {{post.title}} </a> </li> {%endfor%} <ul>

andc

e .com/blog_engine/page/ ep-10-

b- empla e /

7/11

12/23/11

S ep 10: S b- empla e

{%else%} <p>Therearenopostsin{{date|date:"Fo\fY"}} </p> {%endif%} {%endblockcontent%} Okay,weusedthedatetoderivethetitletag,makingitunique foreachmonth.And,attheendwegaveanerrormessageif themonthdidn'thaveanyposts. Inthatsecondone,takenoteofthe'o\f'.Whatisthatallabout? Well,simple,wehadtoescapethe'f'inorderforitnottogiveus amonthoutput.So,inourHTMLitwilloutputJulyof2010.Just threwthatinforfun,butyoucansee,onceyoupasssome valuesintothetemplatefromtheviews,youalmostneedtohold yourselfbackfrombeingtocreative. Okay,monthwaseasy,letsdoyear {%extends'base.html'%} {%blocktitle%}Postsin{{by_month.1|date:"Y"}} {%endblock%} {%blockcontent%} {%ifpost_error%} {{post_error}} {%else%} {%ifby_month%} {%foriinby_month%} {%forkey,valueini.items%}<b>{{key|date:"M" }}</b> {%ifvalue%} <ul> {%forxinvalue%} <li> <ahref="{{x.get_absolute_url}}"title="{{x.title}}"> {{x.title}} </a> </li> {%endfor%} </ul> {%else%} Therewerenopostsin{{key|date:"F"}} {%endif%} <br> {%endfor%} {%endif%} {%endif%} {%endif%}

andc

e .com/blog_engine/page/ ep-10-

b- empla e /

8/11

12/23/11

S ep 10: S b- empla e

{%endblockcontent%} Ididn'tlinktoeachmonthinhere,butIamsurethatyou'llfind thatsimpletodoifyouwantedto.Don'twastetomuchtimeon makingthispagereallynice,youprobablyaren'tgoingtohavea linktotheseyearpages,theyarejusttheresothatwhenvisitors startchoppingyoururlatlogicalpoints,theyhavesomelogic. Forthatreason,itmakessensetojustpointpeoplestraightto theposts.That'swhatIthink,ofcourse,youbuildyourblog yourway. Iamsurethatthe'year.html'waseasytofollow.Letsdothetwo categoryones,andthenI'llleavethetagonestoyouagain. 'category.html' {%extends'base.html'%} {%blocktitle%}Categories{%endblock%} {%blockcontent%} {%ifcategories%} <ul> {%forcategoryincategories%} <li> <ahref="/category/{{category.name.lower}}/" title="{{category.name.capitalize}}"> {{category.name.capitalize}}</a> </li> {%endblockcontent%} In'category.html'wesimplyjustgivealistofcategories.Iliketo besureaboutlowercaseanduppercase,andthisisagood timetousethat,sinceIalwaysaddthecategoriesaslowercase (makesbetterurls),butcapitalizethemwhendisplayingthem. DjangodoesthePythonlikecapitalize,lower,andupperthings forusintemplates.Nice Notethatthougheasy,wedidmakeabitmoreeffortwiththis one,weprovidedlinkstothesinglecategories(forwhowe'll writetemplatesnext).Categoriesissomethingpeoplewilllook upandyoumayprovidelinksto,sotheyareworthworkingon. Nextup,'one_category.html' {%extends'base.html'%} {%blocktitle%}Category{{category.capitalize}} {%endblock%} {%blockcontent%} <h3> PostsundertheCategory<span

andc

e .com/blog_engine/page/ ep-10-

b- empla e /

9/11

12/23/11

S ep 10: S b- empla e

style="color:red"> {{category.capitalize </span> </h3> {%ifposts% <ul> {%forpostinposts% <li> <ahref="{{post.get_absolute_url "title="{{ post.title "> {{post.title </a> </li> {%endfor% </ul> {%endblockcontent%

Andthereyouhaveit.Thereissomuchelsethatyoucanadd tothetemplates,andwearen'tdoneyettotally,butfornow,lets moveon.Ifyouhavebeendiligentlyfollowingthistutorialto here,youaredyingtoseeitallworking.Wearealmostthere. Don'tforgetthatforeachtemplateyouwrite,youneedtogo backtotheview,andchangethetemplate(from'base.html'to 'blog/whatever.html')towhichitpointstotheoneyouhave written.Okay,therearetwoexceptions,letsdealquicklywith thesetwopages. Thefirstisyour404page.Ifyouarewritingwebsites,Iamsure youknowwhata404is,butjustincaseyoudon't,a404isa HTTP'pagenotfound'errorresponse.Thismeanstheuser foundyourserver(intherequest)buttheactualpagedidn't exist.Apagelikethis http://sandcurves.com/how_to_milk_a_cow/isanexamplewe don'thaveanHTMLfilelikethat(okay,ifyoudo,youarean exceptionstrangeperson).No,jokesaside,whatarewegoing todowhensomeoneasksapagewedon'thavewe'llpolitely tellthemthatwedon'thavethatpage. Inyourmaintemplatedirectory,createanewfilecalled,you guessed,404.html.Now,Iamgoingtobereallyboringhere andtellyouthatwearesimplygoingtocopy,verbatim(it's undergnufreedocumentlicense),whatisintheDjangoBook sitefora404page. {%extends"base.html"% {%blocktitle% Pagenotfound{%endblock% {%blockcontent% <h1>Pagenotfound</h1> <p>Sorry,buttherequestedpagecouldnotbe found.</p> {%endblock%

andc

e .com/blog_engine/page/ ep-10-

b- empla e /

10/11

12/23/11

S ep 10: S b- empla e

and,youguessed,a500page.The500pageshouldn'trely onDjangoworkingproperly,itisanerrormessagereportingthat thereisaservererror.SowritethisoneinpureHTML.Tosave timehere,Iwillagainjustcopythe500pagefromtheDjango Booksite(exceptI'llchangethedoctypetoamoreHTML5like version,whereyoucandowhatyoulike.)

<!DOCTYPEhtml> <htmllang="en"> <head> <title>Pageunavailable</title> </head> <body> <h1>Pageunavailable</h1> <p>Sorry,buttherequestedpageisunavailable duetoaserverhiccup.</p> <p>Ourengineers(Me,Myself,andI)havebeen notified,socheckbacklater.</p> </body> </html>

Share | PreviousPage|ReturnToContentsPage|NextPage
Copyright20102011VernonSwanepoel|Djangopowered|WrittenwithEmacsonDebian| HostedbyIntegrit Namibia|Subscribe

andc

e .com/blog_engine/page/ ep-10-

b- empla e /

11/11

12/23/11

S ep 11: W i e he U lconf

NewHere? Subscribe|AboutMe|Twitter|Contact

Sandcurves
BloggingNuts&Bolts VernonSwanepoel'sBlog

Step11:WritetheUrlconf
Okay,closeallthosefileswithtemplatesandallthat.Weare nowgoingtowriteoururls.Now,ifyouhavefollowedalong diligently,youhavealready'written'theurlsintheviewsasa commentstartingeachview.Wenowhavetogotthetheurls.py fileandmapthemtothoseviews. Openyoururls.pyfileinthemain'zing'directory.Addthelinein red. fromdjango.conf.urls.defaultsimport* fromdjango.contribimportadmin admin.autodiscover() urlpatterns=patterns('',(r'^admin/', include(admin.site.urls)), (r'^',include('zing.blog.urls')), ) Actually,allwehavedonenowistelltheurls.pyfilethatanything thatdoesn'tmaptotheadminsite,we'lldealwithunder 'blog.site.urls'. Well,inordertodothat,weneedtowritethatpythonfile.One thingalwaystorememberisthatitisalljustPython,andsoyou cangetcreative.Youcanchangefilenames,usedifferent directories,whateveryouwant,solongasyouimporttheright thingwhenyouneedit. Asaruleofthumb,Iwouldsay,sticktoDjango'sconventions unlessitisactuallymoreclearnotto.Mostofthetime,ifyou starttochangethingsaround,youaregoingtoconfuse yourself. Inthiscasewearen'tdoingsomethingradical,wearejust writingsomeofourviewsinthe'blog'directory. Okay,gointoyour'blog'directory,whereyouhavetheviews.py, models.pyandadmin.pyfilesandcreateanewonecalled 'urls.py'. fromdjango.conf.urls.defaultsimport*

Sandcurves
Home AboutMe Topics Contact Blogroll

About
My nameis Vernon Ilivein

NamibiaI'mapassionate blogger,computer enthusiast,naturalistand fatherSandcurvesismy personalwebsiteandblog More

BloggingProject
MeaningfulBlogProject Linuxandopensourse

andc

e .com/blog_engine/page/ ep-11-

i e-

lconf/

1/3

12/23/11

S ep 11: W i e he U lconf

urlpatterns=patterns('', (r'^$',list), (r'^archive/(?P\d{1,2}/$',list), (r'^\d{4}/d{1,2}/(?P.*)/$',detail), (r'^(?P\d{4})/(?P\d{1,2})/$',month), (r'^(?P\d{4})/$',year), (r'^category/$',category),(r'^category/(? P.*)/$',one_category),(r'^tag/$',tag), (r'^tag/(?P.*)/$',one_tag),) DependingonyourfamiliaritywithPython,thisshouldn'tbeto hardatthispointtofigureout.Theregularexpression(whichI willnotcoverhere,butifyoudon'tknowwhatitis,dolookitup itisfun)mapstoaspecificurl. Simplyput,whensomeonerequestsaspecificurl,thaturlis checkedinthisfileandwhenamatchisfound,itissenttothe view,fromwerethepageisrenderedbypassingvaluestothe templates. Weknowwhichviewtousebecausewespecifyitattheendof eachofthetupleswithinthepatternstuple.So,ifyouaskfor thehomepage,itisgoingtomatchthefirstone(becausethere isnothingbeyondthedomainname,whichistruncatedforthe urls.So,itwillusethe'list'functionintheviews.pyfile,which,in ourcase,willusethe'list.html'templatetoextendthe'base.html' template. Now,ifallhasgonewell,youhaveacomplete,workingwebsite. Ifyouopenyourterminal,andtyperunserver,youshouldbe abletotryouteachurl. vernon@slick:~/project/zing$pythonmanage.py runserver Ifyouarehavingproblems,lookcarefullyattheerrormessages thatDjangoisgivingyou.Note,youarenotgoingtobegetting your404and500pagesthatyouwroteyet,we'llgettothat whenwestartdeployingthesiteonaserver.Fornow,Django's errormessagesaremuchmoreuseful,theyaregoingtotellyou whatyoudidwrong(ordotheirbesttotry.)Askmequestions, andI'llhelpwhereIcan,butalsodigintoDjango's documentationalittle. Resisttheurge,Ithink,togettocreativeatthispoint.Thetough partisgettingeverythingtoworkwellwithaproperwebserver, whichwe'llgettoinabit.

T o ial
BlogEngineTutorial

KeepUp
SubscribebyEmail SubscribebyFeed

W i eOnSandc
G e Po onmyblog

Wo k
IworkatandBeyondasthe managerofourWindhoek office.Ifyouwanttoknow moreaboutNamibiaand theandbeyondoperations inNamibia,visitour Namibiapagesonthe website.

Ad

Blog
Visitthee pertcommunit for datamanagementand businessanal tics.
.AllAnal tics.com

DjangoScalablePla fo m
Eas deplo mentforDjango apps.P thon2.6andgit integration.
.nuagehq.com

Share | PreviousPage|ReturnToContentsPage|NextPage

andc

e .com/blog_engine/page/ ep-11-

i e-

lconf/

2/3

12/23/11

S ep 11: W i e he U lconf

Copyright 20102011VernonSwanepoel|Djangopowered|WrittenwithEmacsonDebian| HostedbyIntegrit Namibia|Subscribe

andc

e .com/blog_engine/page/ ep-11-

i e-

lconf/

3/3

12/23/11

S ep 12: Add commen

NewHere? Subscribe|AboutMe|Twitter|Contact

Sandcurves
BloggingNuts&Bolts VernonSwanepoel'sBlog

Step12:Addcomments
Now,Djangocomeswitharatherfunwaytoworkwith comments,butIamgoingtosimplycopoutatthispoint.You canlearnitifyoulike:Django'sCommentFramework Iwouldrecommend,rather,thatyougowithathirdpartyappin thiscase.Itisgoingtosaveyoualotoftime,andwillmake creatingfeedsandsocialmediagizmossomucheasier,and giveyoutimetoactuallywriteblogpostsorbuildanothersite withDjango. Ifyouareconsideringthirdpartyapps,themainonespeoplein theDjangocommunityseemtouseareIntenseDebateand Disqus. Ireallycouldn'tsaywhichisbetter.IamusingIntenseDebate, andhaveenjoyeditsofar. Theyarereallyeasytouse,andyoucansimplygototheir website,andfollowtheinstructions.Thecode,atleastfor IntenseDebateislinkedtoyoururl,whichmeansyouhavelittle controloverit,buttheydoprovideaccesstoit'sobjectsand someniceCSSstuff.Sofar,allIhavedoneisstickitinandlet itdoit'sthing.Ifyouwanttodothesame,thetemplateyou needtoputitonisthe'detail.html'page.Simplyslotthestuff theygiveyouintotheareabelowthe'post.body|safe'bit,and youareallset. IfyouwantsomehelpwithDjango'sactualcomments,well,you arewelcometoaskme.Itisn'tthathardtosetup,butitisalittle extrawork.
NamibiaI'mapassionate blogger,computer enthusiast,naturalistand fatherSandcurvesismy personalwebsiteandblog More

Sandcurves
Home AboutMe Topics Contact Blogroll

About
My nameis Vernon Ilivein

Share | PreviousPage|ReturnToContentsPage|NextPage

BloggingProject
MeaningfulBlogProject Linuxandopensourse

andc

e .com/blog_engine/page/ ep-12-add-commen /

1/2

12/23/11

S ep 12: Add commen

Tutorials
BlogEngineTutorial

KeepUp
SubscribebyEmail SubscribebyFeed

WriteOnSandcurves
GuestPostonmyblog

Work
IworkatandBeyondasthe managerofourWindhoek office.Ifyouwanttoknow moreaboutNamibiaand theandbeyondoperations inNamibia,visitour Namibiapagesonthe website.

Ads

GetNewCustomersOnline
AdvertiseOnGoogle.Get 1500INRAdvertisingCredit WhenYouSignUp
www.Google.com/AdWords

Ven ZendPackage
Webdevelopmentstartupkit. Savethousandsin developmentcost.
www.ven onsolution.com/

Copyright 20102011VernonSwanepoel|Djangopowered|WrittenwithEmacsonDebian| HostedbyIntegrit Namibia|Subscribe

andc

e .com/blog_engine/page/ ep-12-add-commen /

2/2

12/23/11

S ep 13: Add R

NewHere? Subscribe|AboutMe|Twitter|Contact

Sandcurves
BloggingNuts&Bolts VernonSwanepoel'sBlog

Step13:AddRss
Okay,IcopedoutonComments,andtrustme,Ididthatfor goodreason.ButIamnotleavingyoualonewitheverything. LetsgetsomeRSSfeedsdone.LaterwhenyouhaveRSSyou canhockituptosomethinglikefeedburner,sothatyouhave nicestatsandaccesstoallsortsofwaystopromoteyoursite. Buttodothat,wefirstneedsomeplainoldRSS. YoucouldwritetheRSSyourself,knowingwhatyoualready knowaboutPythonandDjango,aswellasalittlebitofxml formatting.I'msure,ifyouarewritingablog,youareawareof RSSandalittleofhowitworks.Ifyoudon't,youalsowillnot learntomuchhere.Openupyourmainurls.pyfile(theonein thezingdirectory).Addthelinesinred fromdjango.conf.urls.defaultsimport* fromzing.blog.feedimportZingFeed fromdjango.contribimportadmin admin.autodiscover() urlpatterns=patterns('',(r'^admin/', include(admin.site.urls)), (r'^',include('zing.blog.urls')), (r'^feed/$',ZingFeed()), ) Ifyouwereobservant,youwouldseethatweimportedafilethat doesn'texist,'zing.blog.feed'.So,letsmakethattherefile. Gointoyourblogdirectory,andopenupanewfileinyourtext editorcalled'feed.py',andaddallofthefollowing. fromdjango.contrib.syndication.viewsimportFeed fromzing.blog.modelsimportPost classZingFeed(Feed): title="MyZingSiteFeed" link="/" description="Zingsite,poweredbyVernon's DjangoRecipe" defitems(self):
NamibiaI'mapassionate blogger,computer enthusiast,naturalistand fatherSandcurvesismy personalwebsiteandblog More

Sandcurves
Home AboutMe Topics Contact Blogroll

About
My nameis Vernon Ilivein

BloggingProject
MeaningfulBlogProject Linuxandopensourse

andc

e .com/blog_engine/page/ ep-13-add-

1/2

12/23/11

S ep 13: Add R

returnPost.objects.order_by("published")[:5] defitem_title(self,item): returnitem.title defitem_description(self,item): returnitem.description defitem_link(self,item): returnitem.get_absolute_url() Andthatisallthereistothat.Openupyoursiteinyour browser,andgotowhateveritis,127.0.0.1:8000/feed/,andyou shouldbeallset.Onlythingis,allthebeautifulRSSthatyou havewrittenisjustforyou,sinceyoursiteisn'tliveonthe internetyet. So,thenextstep,then,istochangethat.

Tutorials
BlogEngineTutorial

KeepUp
SubscribebyEmail SubscribebyFeed

WriteOnSandcurves
GuestPostonmyblog

Share | PreviousPage|ReturnToContentsPage|NextPage

Work
IworkatandBeyondasthe managerofourWindhoek office.Ifyouwanttoknow moreaboutNamibiaand theandbeyondoperations inNamibia,visitour Namibiapagesonthe website.

Ads

Do nloadGoogleChrome
Searchingisfastandeas ith Google's ebbro ser.
.Google.com/Chrome

BarnesJohn
Visitthee pertcommunit for datamanagementand businessanal tics.
.AllAnal tics.com

Copyright20102011VernonSwanepoel|Djangopowered|WrittenwithEmacsonDebian| HostedbyIntegrit Namibia|Subscribe

andc

e .com/blog_engine/page/ ep-13-add-

2/2

12/23/11

S ep 14: Upload o a e

NewHere? Subscribe|AboutMe|Twitter|Contact

Sandcurves
BloggingNuts&Bolts VernonSwanepoel'sBlog

Step14:Uploadtoaserver
Thisisthehardeststep,Iguess,becausetherearesomany differentservers,andtheyhavedifferentsetups.Iamgoingto giveveryspecificadviceforwhatittookformetogetmy websitesrunningonserversrunbyHostgator. LikeIsaidbefore,thisisnoplugforthem,itissimplybecauseI runsomeofmywebsiteswiththem,andhadtogothrougha ratherlargelearningcurvetogetitdone. Ialsohavetoadmit,Iamkindofstupidaboutthisstuff.Idon't understandtheinsandoutsofApacheverywellatall.Ihave readsomeofthedocumentation,butthereisalotof documentationandIdon'thostssites,Ionlywanttobeableget itonthere,notgethackedandservemysite.Iwouldratherbe buildingnewappsandaddingcontenttomywebsitesthan wastetimebecominganApacheguru.So,followthisbitifyou like,butyoumaywellbebetteroffaskingsomeoneelse. I'lladdhere,ifyouarethemotherofallApachegurus,andyou wanttorewritethissectionforme,well,youwouldrock TherearetwowebpagesthatbasicallyspelloutmostofwhatI amgoingtosayhere,andyoucanratherworkwiththemifyou like. support.hostgator.com/articles/djangowithfastcgi djangobook.com/en/2.0/chapter12/ Okay,letsdosomepreparationbeforeweactuallychange anythingontheserver.I'llmespellthisstuffoutinpointform: Firstup,beforewestarttogetoursiteready,makesure, withyourHostgatorsite,thatyouhavetherightpackage tobeabletorunawebsitewithDjangoandfastcgi. Okay,nowaskyourcontactpersonforFLUP,fastcgi,and MySQLdb. YouwillalsoneedtohaveSSH,whichyoumayhaveto payextrafor. Ifyoudon'talready,youwillneedtoknowyourusername andpasswordforthewebsite. Underyourprojectdirectory,wherewecurrentlyhave nothingbutthemain'zing'directory,createannew
NamibiaI'mapassionate blogger,computer enthusiast,naturalistand fatherSandcurvesismy personalwebsiteandblog More

Sandcurves
Home AboutMe Topics Contact Blogroll

About
My nameis Vernon Ilivein

BloggingProject
MeaningfulBlogProject Linuxandopensourse

andc

e .com/blog_engine/page/ ep-14- pload- e

e /

1/7

12/23/11

S ep 14: Upload o a e

directoryandcallit'guts'.Ifyoudon'tlikethatname,call it'public_html'oranythingelse,butwearegoingtouse thisforthenoneDjangostuff. Underthatdirectory,openaterminalandtypethe following: vernon@slick:~/project/guts$ftp your_domain_name Where'your_domain_name'is,ofcourse,yourdomain name.Inmycase,Iwouldbetypingsandcurves.com. Notethelackof'http://'infrontofit.Justthenameand thedot_whatever(.com). Youmayhavesomefancydandyftpprogramsuit yourself.Iwillstickwithbasicterminalftping,justbecause it'llhelpusstayonthesamepage. Okay,dolikeso: Connectedtosandcurves.com.220 WelcometoPureFTPd[privsep][TLS] 220Youareusernumber1of50allowed. 220Localtimeisnow05:08.Serverport: 21. 220Youwillbedisconnectedafter15 minutesofinactivity. Name(your_domain.something:your_name): your_username andthen 331Useryour_usernameOK.Password required Password:your_password Okay,likeIsaid,Iamassumingthatyoursetupisjustlike mine,andsowearegoingtodownloadsomefilesfrom thelocationIhavethem.Ifyoudon'tfindthesefiles whereIamtellingyou,askyourcontactstohelp.Forthe mostpart,thiskindofsetupisfairystandardforApache sharedhostenvironments. You'llhaveyournicelittle'ftp>"prompt,andsonowdo this: ftp>get.bashrc local:.bashrcremote:.bashrc 200PORTcommandsuccessful 150Connectingtoport56619 226Filesuccessfullytransferred 2260.012seconds(measuredhere),17.79 Kbytespersecond 214bytesreceivedin0.01secs(14.6kB/s)

T o ial
BlogEngineTutorial

KeepUp
SubscribebyEmail SubscribebyFeed

W i eOnSandc
G e Po onmyblog

Wo k
IworkatandBeyondasthe managerofourWindhoek office.Ifyouwanttoknow moreaboutNamibiaand theandbeyondoperations inNamibia,visitour Namibiapagesonthe website.

Ad

Wan ToDe ignA Web i e?


DesignYourWebsiteB The BestWebDesignCompan In India.SeeMore

Don23DT aile
NowPla ingDon2Trailersin 3D.CatchItAllonYouTube!
outube.com/Don2

andc

e .com/blog_engine/page/ ep-14- pload- e

e /

2/7

12/23/11

S ep 14: Upload o a e

ftp> Okay,thatfileisn'tsoimportant,butthenextoneis.We willneedtochangedirectoriesontheserver,andthen fetchthefile.Changingdirectoriesontheothersiteisjust thesameasdoingitonyourownmachine.Ifyouneeded tochangedirectoriesonyourownsite,whileusingftp,use 'lcd'instead.FTPisveryeasytoworkwith,andifyou wanttobeawebguru,youshouldknowyourFTPbasics verywell. ftp>cdpublic_html 250OK.Currentdirectoryis/public_html ftp>get.htaccess local:.htaccessremote:.htaccess 200PORTcommandsuccessful andsoon ftp>bye 221Goodbye.Youuploaded0and downloaded2kbytes. 221Logout. vernon@slick:~/project/guts$ Youcanalwayslogoutofftpusingtheterm'bye'or 'exit'.&nbps Okay,I'mgoingtoshowyoubasicallywhatIhaveinthere: #FrontPage AddHandlerfcgidscript.fcgi Options+FollowSymLinks RewriteEngineOn RewriteBase/ IndexIgnore.htaccess*/.??**~*# */HEADER**/README**/_vti* orderdeny,allow denyfromall allowfromall orderdeny,allow denyfromall

AuthNamedomain_name.com AuthUserFile /home/user_name/public_html/_vti_pvt/service.pwd AuthGroupFile /home/user_name/public_html/_vti_pvt/service.grp AddTypetext/xpython.py

andc

e .com/blog_engine/page/ ep-14- pload- e

e /

3/7

12/23/11

S ep 14: Upload o a e

RewriteRule^media/(.*)$[L] RewriteRule^adminmedia/(.*)$[L] RewriteCond%{REQUEST_URI !(zing.fcgi) RewriteRule^(.*)$zing.fcgi/$1[QSA,L] Whatisgoingtobeimportantisthosefirstfewlines(I thinklines2to5)andthenallthestuffinthelastfewlines (thewholelastblock,wherethelinesstartwith 'RewriteRule'). Thestuffinbetweenisprobablysimilartowhatyouhave alreadyinthatfile.Sojustchangeyourfirstandlastbits tobeexactlylikeminewherethereferenceto'zing.fcgi' canstay'zing'orbechangedtowhateveryoulike. Thenextstep,then,istocreatethatfcgifile,soopenupa fileinthe'guts'directorycalled'zing.fcgi'(ofcourse, changingthenametowhateveryoucalleditinyour .htaccessfile. Okay,thisnextbitassumesthatyourpythonpathisthe sameasmine.Youcancheckonthat.AtthemomentI stillhavepython2.4ontheserveryoumayneedtocheck that(youcanask,orsshandrunapythonshell,whichwill showyoutheversion). #!/usr/local/bin/python importos,sys sys.path.insert(0,"/usr/lib/python2.4") sys.path.insert(0,"/home/domain_name/dj") sys.path.insert(0, "/home/domain_name/dj/django") sys.path.insert(0, "/home/domain_name/dj/project") sys.path.insert(0, "/home/domain_name/dj/project/zing") #SettheDJANGO_SETTINGS_MODULE environmentvariable. os.environ['DJANGO_SETTINGS_MODULE'] ="zing.settings" fromdjango.core.servers.fastcgiimport runfastcgi runfastcgi(method='threaded', daemonize='false') Next,copyyoursettings.pyfilefromthe'zing'directoryto the'guts'directory.Whenwerunthesiteonthehost server,forthemostparttheonlythingwewanttohave differentisthesettings.pyfile.Sowearegoingtokeep theoneinthe'zing'directoryasitis,andmakethe neededchangestotheotheroneforwhatweneedonour site. Thereisoneotherfilewearegoingtokeepadifferent versionofonourhomesitetoourserver'ssite,the base.html.Socopyitformthe'template'directorytothe 'guts'directory. ThereasonisthatwewanttoseparateCSSfromthe

andc

e .com/blog_engine/page/ ep-14- pload- e

e /

4/7

12/23/11

S ep 14: Upload o a e

HTML.Lookforthislinewewroteohsolongago: <linkrel="stylesheet"type="text/css" href="/media/css/style.css"> Copyallthecontentbetweentheopen<style>tagandthe closing</style>tag.Now,pastethatintoafilecalled 'style.css' /*ZingStylesheet*/ /*Page*/ body{padding:0margin:0fontfamily:Arial, Helvetica,Tahoma,sansserif /*Titlesection*/ #title{float:leftwidth:100%padding:0margin:0border:0border bottom:1pxsolid#cccccc #titleh1{padding:10px0050pxfont size:60ptmargin:0fontfamily:"MyriadPro", Arial,Helvetica,Tahoma,sansserif #titleh2{margin:0padding:0text align:center /*Contentsection*/ #content{float:leftborder:0margin:0padding:10px 2%02%width:75% /*Sidebarsection*/ #sidebar{float:leftborder:0borderleft:1px solid#ccccccpadding10px2%0 2%width:20%margin:0 /*Footersection*/ #footer{float:leftborder:0bordertop:1px solid #ccccccpadding:0margin:0width:100%text align:center

Forthemostpart,Ihavetriedtoleaveoutasmuch unnecessarystuffaspossible,butonethingthatmakes suchadifferenceishavingaliaseswhenyouareworking withssh.Underbash(theterminalthingi)wecanhave onewordthatwedefinetomeansomescripttorun.In ourcase,allwearegoingtodoissetsome'cd' commands,sothatwecanquicklygettothedirectories usedmost. Openthe'.bashrc'file(rememberthatwithboththisfile andthe.htaccessfile,theyarehiddenfilesunderlinux.If youhaveaproblemseeingthem,justrun'lsa'inour terminaltoseethehiddenfileslistedand'emacs.bashrc' toopenitupwithemacs. Atthebottomofthefile,justappendtheselines,andthen closeandsaveit.You'llhavetochange'user_name'for yoursetup. #Userspecificaliasesandfunctions aliaszing='cd /home/user_name/dj/project/zing'

andc

e .com/blog_engine/page/ ep-14- pload- e

e /

5/7

12/23/11

S ep 14: Upload o a e

aliasstylo='cd/home/user_name/media/css' Sofarwehaven'tbrokenanythingonourwebserveryet.Take adeepbreath,playSodoku,gogetcoffee,clearyourhead.We areabouttostarttinkeringwiththeinsides,theguts,ofyourhost server. Sshisafantastictoolwhereyouhavecommandlineaccessto remotecomputersthroughasecuretunnel.UnlikeFTP,where wewerejustbringingandtaking,withSSHweareactuallygoing togoontoourhostserver'scomputerandtinker. WithSSHaccesstotheservercomputeryoucanonlydoa limitedamountofthing,soIdon'tthinkyouneedtoworryabout breakingtheircomputer(Ihope),butyoucantotallydestroy yourownwebsiteactually,whenwestartour,thatisexactly whatwearegoingtodoanyway.But,hopefully,we'llalsobe gettingittoworkverysoon. Thefirsttimeyoutrytoconnectitisgoingtoaskyouifyouwant tocontinue,becauseitdoesn'tknowthesite.Answer'yes'of course.Togetintoyourwebserverwithssh,dothefollowing: vernon@slick: /project/guts$sshp2222 username@domain_name.com Andtoexit,simplytypeexit: whatever@whatever: $exit Remembereachtimetoexit,sameasFTP. Okay,now,letsgetthingsgoing.sshintoyourserveragain(it doesn'tmatterfromwhichdirectoryyouareinyourhome computerrightnow). Youareatyourrootdirectorywhenyoulogin.Thefirstthing youwanttodoisseeifpythonisworking.Attheterminal,type 'python'andhitenter.ItshouldenterthefamiliarPythonshell. NextistoseeifDjangoisinstalled.WhilestillinPython,type "importdjango"Ifnothinghappens,andpythonjustmovesonto anemptypythonprompt('>>>')thendjangoisthereandyou don'thavetoworry. Hit'Ctrld'togetoutofpython,andmakeanewdirectory('mkdir dj')called'dj'.cdintoit.Ifyoudidn'thaveDjango,youcangetit withsvn.Seethispagetohelpinstallthedevelopmentversion. Okay,ifthathasallgonewell,letsmakeourprojectdirectory 'mkdirproject'andcdintoit. Createyournewdjangoprojecthere,with'djangoadmin.py startprojectzing'.Thisisthesecondtimearound,sothisshould befamiliarground.

andc

e .com/blog_engine/page/ ep-14- pload- e

e /

6/7

12/23/11

S ep 14: Upload o a e

Again,repeatingourselves,makethedirectory'mkdirtemplate' forthetemplates.Thenmakethe'blog'subdirectory,'mkdir template/blog' Andourblogapplication,'pythonmanage.pystartappblog'. Typecdtogetbacktoyourrootdirectory,andcreateanew one,'media'.Thenmakeasubdirectory,'mkdirmedia/css'And thenexit.

Share | PreviousPage|ReturnToContentsPage|NextPage
Copyright20102011VernonSwanepoel|Djangopowered|WrittenwithEmacsonDebian| HostedbyIntegrit Namibia|Subscribe

andc

e .com/blog_engine/page/ ep-14- pload- e

e /

7/7

12/23/11

S ep 15: Upload O

Si e

NewHere? Subscribe|AboutMe|Twitter|Contact

Sandcurves
BloggingNuts&Bolts VernonSwanepoel'sBlog

Step15:UploadOurSite
Now,wearegoingtodoasimplebitofftp.Startinthe'guts' directory.ftpintoyoursite,and,usingthekeyword'put'putthe .bashrcfileup. cdinto'public_html'andput.htaccessandzing.fcgiintothat directory. From'public_html'directory,type'cd../media/css'togetintoour cssdirectoryand'putstyle.css' Thelastfileingutsweneedtoworryaboutfornowisthe 'base.html'file.Ifyouarestillinthe'css'directoryonyour server,type'cd../../dj/project/zing/template/'togettothe templatedirectory,andputthebase.htmlfilethere. Waitfirstwiththesettings,wefirsthavesomedatabasestuffto takecareof. Now,wewanttoputthestuffupinourmaindjangoproject,so, from'guts'weneedtotype'lcd../zing'togettozing.Weneed tobeinthesamedirectoryontheserver,so'cd../'(outof 'template')togetthere.Theonlythingweneedtobotherwith hereisthe'urls.py'file,so'puturls.py'. Onethingtonotehereisthatwearenotgoingtousethe 'zing.db'forthedatabase,itwillbeaMySQL,andwellgettothat soon. cdintothe'blog'directory(andlcdthesametogetthereonyour homecomputer).Hereyoucanletrip,andratherthanftpone thingatatime,type'mftp*.py'.Specifythefileendingsothatit doesn'tputupthepycfilesandthingslikethat.Itwillaskyouif youwanttoputupthefile,andtosayyesyoucanjusthitenter. Iftherewasafileyoudidn'twanttoputup(forexample,we don'tneedtoputupthe__init__.pyfile)thenjustan'n'and enterwillsuffice.The'*'isawildcard,ofcourse'doitall'. Now'cd../template/blog'and'lcd../template/blog'and'mftp *.html' Exitssh.
MeaningfulBlogProject Linuxandopensourse

Sandcurves
Home AboutMe Topics Contact Blogroll

About
My nameis Vernon Ilivein

NamibiaI'mapassionate blogger,computer enthusiast,naturalistand fatherSandcurvesismy personalwebsiteandblog More

BloggingProject

andc

e .com/blog_engine/page/ ep-15- pload-o

- i e/

1/2

12/23/11

S ep 15: Upload O

Si e

Share | PreviousPage|ReturnToContentsPage|NextPage

Tutorials
BlogEngineTutorial

KeepUp
SubscribebyEmail SubscribebyFeed

WriteOnSandcurves
GuestPostonmyblog

Work
IworkatandBeyondasthe managerofourWindhoek office.Ifyouwanttoknow moreaboutNamibiaand theandbeyondoperations inNamibia,visitour Namibiapagesonthe website.

Ads

Pe a ack
Onepetab teinasinglerack underoneNamespaceor Volume.
aberdeeninc.com/abcatg/petarack.htm

o eYo

file Online

Getonlinedatastorageand databackup.
www.storage.sif services.com

Copyright20102011VernonSwanepoel|Djangopowered|WrittenwithEmacsonDebian| HostedbyIntegrit Namibia|Subscribe

andc

e .com/blog_engine/page/ ep-15- pload-o

- i e/

2/2

12/23/11

S ep 16: Se

p ne

Da aba e

NewHere? Subscribe|AboutMe|Twitter|Contact

Sandcurves
BloggingNuts&Bolts VernonSwanepoel'sBlog

Step16:SetupnewDatabase
Forthedatabase,onceagain,Iamgoingtoassumethatyour setupisthesameasmine.Ifitisn't,hopefullyitiscloseenough togiveyouahintofwhatyouneedtodo. Okay,insteadofdoingallofthiswithssh,letsjustgotocpanel (thisis,assumingyouhavecpanel)andgoingtothesection 'Databases',whichseemstobeastandard.Clickon'MySQL Databases'Itissoeasy.Justgotowhereitsays'Createanew database'.Whileyoudoso,notedownthedatabasename (whichisusuallythesiteusernamewithanunderscoreandthen thenameyougive,suchas'vernon_zingdb'orwhatever), username,passwordandsoon. Whenyouaredone,logoutofcpanelandgointoyourguts directoryandopenthe'settings.py'filethatisthere. Underthe'DATABASE={'enterthefollowing:

Sandcurves
Home AboutMe Topics Contact Blogroll

DTBSS={ AAAE 'eal' dfut:{ About 'NIE:'yq' EGN'msl, 'AE:'ennznd'haeyuedduihfrtedtbs. NM'vro_igb,#Tenmonepwtohaaae ' S R : ' h _ s r a e y u c e t d u d r d t b s s i _ p n l , My UE'teuenm_o_rae_ne_aaae_ncae' nameis 'ASOD:'orpswr_o_h_aaae, PSWR'yu_asodfrtedtbs' Vernon 'OT:',#laetinlc HS''evhsoebak Ilivein 'OT:'36, PR'30' Youshouldalsosetthe'DEBUG'to'False',but,maybejustwait alittlebit,letsjustgetitworkingupontheserver. Alsochangethesethreelineshere: MEDIA_ROOT='http://domain_name.com/media' MEDIA_URL='/media/' ADMIN_MEDIA_PREFIX='/adminmedia/' ftpthesettings.pyfilefromgutstoyour'zing'directory. Wearenearingtheendnow.Sshintoyoursiteagain,and

NamibiaI'mapassionate blogger,computer enthusiast,naturalistand fatherSandcurvesismy personalwebsiteandblog More

BloggingProject
MeaningfulBlogProject Linuxandopensourse

andc

e .com/blog_engine/page/ ep-16- e -ne -da aba e/

1/2

12/23/11

S ep 16: Se

p ne

Da aba e

(rememberwhatwetypedinthe.bashrcfile)type'zing'andyou shouldbewhizzedintoyour'zing'directory. Type'pythonmanage.pyvalidate'.Ifyougeterrors,youcan checkyoursettings.pyfileorgethelpfromthehostgatorhelp center.Ortweetme,maybeImissedsomethingobvious. Ofcourse,ifitworks,run'pythonmanage.pysyncdb'.Of course,you'llhavetocreateanewsuperuser,likeyoudid beforeonyourhomesite.Youmaywanttousethesame passwordasyoudidonyourownsite. Exitssh,gotoyour'http://your_domain.com/admin/page,login andseeifitisallgood.Writeafewblogpostsandseeifthey showupasyouexpectedonthesite.You'llprobablywantto addtotheCSS,andmakeitalllookbetter. Ifitallwentwell,youshouldhaveaworkingblog.Nowwrite somethingcrackinginthereandsendmealinktocheckitout.

Tutorials
BlogEngineTutorial

KeepUp
SubscribebyEmail SubscribebyFeed

WriteOnSandcurves
GuestPostonmyblog

Work
IworkatandBeyondasthe managerofourWindhoek office.Ifyouwanttoknow moreaboutNamibiaand theandbeyondoperations inNamibia,visitour Namibiapagesonthe website.

Share | PreviousPage|ReturnToContentsPage|NextPage

Ads

Da aBack p
B ine in elligencee pe ha ing hei ec e i h o . Go!
.AllAnal ic .com

o eYo

file Online

Ge onlineda a o ageand da aback p.


. o age. if e ice .com

Copyright20102011VernonSwanepoel|Djangopowered|WrittenwithEmacsonDebian| HostedbyIntegrit Namibia|Subscribe

andc

e .com/blog_engine/page/ ep-16- e -ne -da aba e/

2/2

12/23/11

Step 17: Awa You Go

NewHere? Subscribe|AboutMe|Twitter|Contact

Sandcurves
BloggingNuts&Bolts VernonSwanepoel'sBlog

Step17:AwayYouGo
Now,goplaywithit. Youcaneitherworkonfileonyourownsystem,orifyouare makingjustquicktweaks,usenanoinsshtoworkdirectlyon filesinyoursystem. Ifyouactuallyfollowedthistutorialallthewaythrough,well done,veryfewpeoplemakeitthroughamassivetutoriallike this.Ihopeyoulearnedalot,butIamalsosureyourealized thatthereissomuchmoretoDjango,nottomentionPython andLinuxitself.Hopefullyitisjustthestartforyou,asitisfor me. FormoreonGimp:gimpologyandthegimpwebsite.

Sandcurves
Home AboutMe Topics Contact Blogroll

Share | PreviousPage|ReturnToContentsPage|NextPage

About
My nameis Vernon Ilivein

NamibiaI'mapassionate blogger,computer enthusiast,naturalistand fatherSandcurvesismy personalwebsiteandblog More

BloggingProject
MeaningfulBlogProject Linuxandopensourse

sandcurves.com/blog_engine/page/step-17-awa - ou-go/

1/2

12/23/11

Step 17: Awa You Go

Tutorials
BlogEngineTutorial

KeepUp
SubscribebyEmail SubscribebyFeed

WriteOnSandcurves
GuestPostonmyblog

Work
IworkatandBeyondasthe managerofourWindhoek office.Ifyouwanttoknow moreaboutNamibiaand theandbeyondoperations inNamibia,visitour Namibiapagesonthe website.

Ads

DesignCoursein12mths
DoGraphics&WebDesign parttimealongwith ourBA BComBScdegree
www.ArenaMultimedia.com

AudiA6Lu ur Sedan
Flawlessdesign&efficienc . Bookatestdriveonlinenow!
www.audialist.in/testdriveA6

Copyright 20102011VernonSwanepoel|Djangopowered|WrittenwithEmacsonDebian| HostedbyIntegrit Namibia|Subscribe

sandcurves.com/blog_engine/page/step-17-awa - ou-go/

2/2

12/23/11

Pa

on hi

o ial

NewHere? Subscribe|AboutMe|Twitter|Contact

Sandcurves
BloggingNuts&Bolts VernonSwanepoel'sBlog

Passonthistutorial
Didyouenjoythistutorial?Doyouthinkthatotherscould benefitfromit?Pleasefeelfreetopassitontoothers. Youcouldhostthewholetutorialonyourownwebsiteifyou like.Ifyougivemecreditandlinkbacktothissite,youare awesome,butIdon'trequireit.Ifyouwantsomehelp,contact meandI'llseeifIcanhelpyougetitupandrunningonyour site.Themainthingyouneedtoconcernyourselfwithis parsingtheHTMLsothatitdoesn'tjustbecomepartofthe HTMLofyourpage. Ofcourse,youdon'thavetohostityourself,ifyousimplylink backtomethatitfantastic.

Sandcurves
Home AboutMe Topics Contact Blogroll

< a he=h p/ ad f" :/ nc e.o cm /lgegn/il=A bo_nie" e" panad ipeDag lin mljno bo idn oil> lgb lig a" Snc ejnoT oil ad Dag a <a />
Share | PreviousPage|ReturnToContentsPage

About
My nameis Vernon Ilivein

NamibiaI'mapassionate blogger,computer enthusiast,naturalistand fatherSandcurvesismy personalwebsiteandblog More

BloggingProject
MeaningfulBlogProject Linuxandopensourse

andc

e .com/blog_engine/page/pa

o ial/

1/2

12/23/11

Pa

on hi

o ial

Tutorials
BlogEngineTutorial

KeepUp
SubscribebyEmail SubscribebyFeed

WriteOnSandcurves
GuestPostonmyblog

Work
IworkatandBeyondasthe managerofourWindhoek office.Ifyouwanttoknow moreaboutNamibiaand theandbeyondoperations inNamibia,visitour Namibiapagesonthe website.

Ads

GetNe CustomersOnline
AdvertiseOnGoogle.Get 1500INRAdvertisingCredit WhenYouSignUp
www.Google.com/AdWords

Don23DTrailer
NowPla ingDon2Trailersin 3D.CatchItAllonYouTube!
outube.com/Don2

Copyright 20102011VernonSwanepoel|Djangopowered|WrittenwithEmacsonDebian| HostedbyIntegrit Namibia|Subscribe

andc

e .com/blog_engine/page/pa

o ial/

2/2

12/23/11

Relevant Links Django

NewHere? Subscribe|AboutMe|Twitter|Contact

Sandcurves
BloggingNuts&Bolts VernonSwanepoel'sBlog

UsefulLinkstoDjangoBlogDevopment
Acompleteblogengineusingdjangoin60minutes Thisisagreattutorial,andfollowstheDRYprincipalvery well.Iworkedthroughthistutorialandlearnedalotfrom it.&nbps60minutes?Ittakesalittlelonger,unlessyou reallyknowyourstuffalready. BuildamicroblogwithdjangoThisisanotheruseful tutorial.Ididn'treadthroughit,soIcan'tsayhowgoodit is.

Sandcurves
AdetaileddjangotutorialblogbasicsHeisanexpert, Iamsureitisgood.Ididn'treadthisoneeither. DjangoTutorialsAlistofDjangotutorials. TheDjangoTutorialGositatthefeetofthemastersof Django,andbecomewise. Django'sDocumentationIamsureIdidn'tneedtoput thislink,ifyoudon'tdipinthedocs,forgetbeingaDjango guru,ever. RunningDjangoonGoogleAppEngineFanof GoogleAppEngine,herearethedocstohelpyouget DjangoandAppengineworkingtogether. DjangoBookThiswasthemainthingIusedtolearn Django,andIfinditreallyuseful. DidyouwriteagoodDjangoTutorial?SendmeaTweet @sandcurvesandI'llcheckitoutandstickupalink. Hereareafewotherrelatedthingsyoumayfinduseful Emacs ThePythonTutorial
NamibiaI'mapassionate blogger,computer enthusiast,naturalistand fatherSandcurvesismy personalwebsiteandblog More Home AboutMe Topics Contact Blogroll

About
My nameis Vernon Ilivein

BloggingProject
MeaningfulBlogProject Linuxandopensourse

sandcurves.com/blog_engine/links/

1/2

12/23/11

Relevant Links Django

DiveIntoPython[outofdate,butsuperforlearning Python] TheGimpImageManipulationProgram Ubuntu ApacheWebServer ReturntothecontentspageoftheDjangoBlogEngineTutorial

Tutorials
BlogEngineTutorial

KeepUp
SubscribebyEmail SubscribebyFeed

WriteOnSandcurves
GuestPostonmyblog

Work
IworkatandBeyondasthe managerofourWindhoek office.Ifyouwanttoknow moreaboutNamibiaand theandbeyondoperations inNamibia,visitour Namibiapagesonthe website.

Ads

Don23DTrailer
NowPla ingDon2Trailersin 3D.CatchItAllonYouTube!
outube.com/Don2

Sams ngMicro a eO ens


Deep&EvenCookingwith SamsungMicrowaveOvens. GetDetailsnow.
www.Samsung.com/in

Copyright 20102011VernonSwanepoel|Djangopowered|WrittenwithEmacsonDebian| HostedbyIntegrit Namibia|Subscribe

sandcurves.com/blog_engine/links/

2/2