django cookbook web development with django - step by step guide
TRANSCRIPT
DjangoCookbookWebDevelopmentwithDjango
StepbyStepGuide2-ndEdition
ByBeauCurtin
Copyright©2016BeauCurtinAllRightsReserved
Copyright©2016BeauCurtin
All rights reserved. No part of this publication may be reproduced, distributed, or
transmitted in any form or by any means, including photocopying, recording, or other
electronic or mechanical methods, without the prior written permission of the author,
except in the case of brief quotations embodied in critical reviews and certain other
noncommercialusespermittedbycopyrightlaw.
TableofContents
Chapter1-Definition
Chapter2-SettinguptheEnvironment
Chapter3-TheAdminInterface
Chapter4-CreatingViewsinDjango
Chapter5-URLMapping
Chapter6-TemplateSystem
Chapter7-Models
Chapter8-PageRedirection
Chapter9-SendingE-mails
Chapter10-GenericViews
Chapter11-FormProcessinginDjango
Chapter12-UploadingFiles
Chapter13-HandlingCookies
Chapter14-SessionsinDjango
Chapter15-MemoryCachinginDjango
Conclusion
Disclaimer
Whileallattemptshavebeenmadetoverifytheinformationprovidedinthisbook,the author does assume any responsibility for errors, omissions, or contraryinterpretations of the subjectmatter containedwithin. The information provided inthisbookisforeducationalandentertainmentpurposesonly.Thereaderisresponsibleforhisorherownactionsandtheauthordoesnotacceptanyresponsibilitiesforanyliabilitiesordamages,realorperceived,resultingfromtheuseofthisinformation.
The trademarks that are used arewithout any consent, and thepublication of thetrademark is without permission or backing by the trademark owner. Alltrademarksandbrandswithinthisbookareforclarifyingpurposesonlyandaretheownedbytheownersthemselves,notaffiliatedwiththisdocument.
Introduction
There has been an increase in the need for web apps, however, most programming
languageswhichsupportappdevelopmentarecomplex.Thismeansthatlongerperiodsof
times are spentwhile developing these apps. Python has a framework called “Django”
whichprovideswebdeveloperswith amechanism to developweb apps in an easy and
quickmanner. So it’s a good idea for you to learn how to use this framework for the
development of web apps, all of which is explained in this book.Make sure that you
installPython2.6.5orhigher.Enjoyreading!
Chapter1-DefinitionDjango is a Python-based web framework used for building web applications of high
quality.Ithelpsusavoidrepetitivetasks,whichmakestheprocessofwebdevelopmentan
easyexperienceandsavestime.
ThefollowingaresomeofthedesignphilosophiesofDjango:
Loosely Coupled- In Django, the aim is to make each element of the stack as
independentaspossible.
Fast Development- The aim is to do whatever it takes to facilitate the fast
developmentofwebapplications.
LessCoding-Lesscodeisusedtofacilitatefastdevelopment.
CleanDesign-TheaimofDjangoistocomeupwithaverycleandesigntomake
developmenteasy.Clearstrategiesareusedduringthewebdevelopmentprocess.
Don’t Repeat Yourself (DRY)- Everything in Django has to be developed in a
singleplace,ratherthanrepeatingitagainandagain.
Chapter2-SettinguptheEnvironment
To set up the environment for development in Django, you have to install and set up
Python,theDjangoandaDatabaseSystem.SinceDjangoisusedfordevelopmentofweb
apps,youalsohavetosetupaserver.
InstallationofPython
ThecodeforDjangoisdesigned100%forPython.Thismeansthatyouwillhavetoinstall
Pythoninyoursystem.ForthoseusingthelatestversionsofeitherLinuxorMacOS,the
Pythonwillhavealreadybeeninstalledforyou.Toverifythis,justopenyourcommand
promptand then type thecommand“python”. Ifpythonhasalreadybeen installed,you
shouldseesomethingsimilartothis:
$python
Python2.7.5(default,Jun172014,18:11:42)
[GCC4.8.220140120(RedHat4.8.2-16)]onlinux2
If you don’t get the above result, make sure that you download and install the latest
versionofPythontoyoursystem.
InstallationofDjango
Thiscaneasilybedone,but thesteps involvedaredeterminedby thekindofoperating
systemyouareusing.PleasenotethatPythonisaplatformthatisplatformindependent.
This is why there is only a single package forDjango, because it canwork on all the
platforms.
InstallationonUnix/LinuxandMacOS
In theseoperatingsystems, theDjangoframeworkcanbe installed in the following two
ways:
UsingthepackagemanageroftheOS,oruse“pip”or“easy_install”,iftheyhave
alreadybeeninstalled.
Manualinstallationbyuseofthearchiveyouhaddownloadedbefore.
Wewillonlyexplorethesecondoption,asthefirstonewilldependonthedistributionof
theOSyouareusing.Ifyouchoosetofollowthefirstmethod,becarefulwiththeversion
oftheDjangothatyouinstall.Itisbesttoinstallthelatestversionoftheframework.
Youcanthenextractandinstallthepackage.Thefollowingcommandsarenecessary:
$tarxzvfDjango-x.xx.tar.gz
$cdDjango-x.xx
$sudopythonsetup.pyinstall
Totestyourinstallation,justexecutethecommandgivenbelow:
$django-admin.py–version
IfyouseethecurrentversionofDjangodisplayedonthescreen,youwillknowthat
everythinghasbeensetupasintended.
InstallationonWindows
OurassumptionisthatyoualreadyhaveyourPythonandDjangoArchiveinstalledon
yoursystem.Beginbyverifyingyourpath.
OncertainversionsoftheWindowsOS,youshouldfirstcheckthatthePATHvariablehas
beensettothefollowing:
C:\Python27\;C:\Python27\Lib\site-packages\django\bin\
However,theabovewillbedeterminedbytheversionofPythonthatyouareusing.The
extractioncanbedoneasfollows:
c:\>cdc:\Django-x.xx
ItisnowtimeforyoutoinstalltheDjango.Forthecommandfordoingthistobe
executed,youmusthaveadministrativeprivilegesoverthesystem.Hereisthecommand:
c:\Django-x.xx>pythonsetup.pyinstall
Theinstallationcanbeverifiedbyrunningthefollowingonthecmd:
c:\>django-admin.py–version
ThecurrentversionoftheDjangoshouldbedisplayedonthescreen.
Forthecaseofsetupofthedatabase,thereisaspecificwaytodoitforanydatabase.
Thereareseveraltutorialsonlineexplaininghowtodothis.Djangoalsocomespre-
configuredwithawebserver.Thiscanbeusedforthepurposeofdevelopingandtesting
webapplications.
CreationoftheProject
ForbothLinuxandWindowsusers,launchyourterminalorcmdandthennavigateto
whereyouneedyourprojecttobelocated.Justexecutethecommandgivenbelow:
$django-adminstartprojectproject1
Theabovecommandwillcreateaprojectnamed“project1”andthiswillhavethe
structuregivenbelow:
Project1/
manage.py
project1/
__init__.py
settings.py
urls.py
wsgi.py
StructureoftheProject
The“Project1”folderisintheprojectcontaineranditismadeupoftwoelements:
•manage.py-thisfileisresponsibleforfacilitatingyoutoperformaninteraction
withyourprojectviathecommandline.Ifyouneedtoviewthelistofcommands
thatcanbeaccessedviathisfile,youcanexecutethefollowingcommand:
$pythonmanage.pyhelp
“project1”subfolder-thisrepresentstheactualPythonpackageforthe
project.Ithasfourfiles:
__init__.py-thisisforPythonanditshouldbetreatedasapackage.
settings.py-thishasthesettingsforyourproject.
urls.py-thishasthelinkstoyourprojectaswellasthefunctionstocall.Itis
justakindofToCfortheproject.
wsgi.py-thisisneededifyouwanttoperformadeploymentofyourproject
viatheWSGI.
SettingUptheProject
Theprojecthasbeensetupinthefoldernamed“project1/settings.py”.Let’sdiscusssome
oftheimportantaspectsthatyoumayhavetosetup:
DEBUG=True
Withtheaboveoption,youwillbeinapositiontosettheprojecttoeitherbeindebug
modeornot.Indebugmode,youwillbeinapositiontogetmoreinformationregarding
theerrorsofaproject.Thisshouldnotbesetto“True”whentheprojectislive.Toenable
yourDjangolightserverservestaticfiles,thishastobesetto“True”.Thisshouldonlybe
doneinthedevelopmentmode.
DATABASES={
‘default’:{
‘ENGINE’:‘django.db.backends.sqlite3’,
‘NAME’:‘database.sql’,
‘USER’:”,
‘PASSWORD’:”,
‘HOST’:”,
‘PORT’:”,
}
}
Intheexamplegivenabove,wehaveusedtheSQLiteengine.Beforeyoucansetupany
newengine,youshouldalwaysensurethatyouhavecorrectlyinstalledthenecessarydb
driver.
Sinceyouhavecreatedandconfiguredtheproject,itisagoodideatochecktomakesure
thatitisworking.Thiscanbedoneasshownbelow:
$pythonmanage.pyrunserver
Chapter3-AppsLifeCycleAprojectismadeupofmanyapplications.Eachoftheseapplicationshasanobjectthat
could equally be used in anyother project.Agood example of this is the contact form
usedonawebsite,asitcanbeusedonotherwebsites.Itshouldbeseenasamodulefora
project.
CreatinganApplication
Ourassumptionisthatyouareintheprojectfolder.Themain“project1”folderissimilar
tothefolder“manage.py”.
$pythonmanage.pystartappmyapplication
At this point, you will have created the application “myapplication” and we can then
createthe“myapplication”folderwiththestructuregivenbelow:
myapplication/
__init__.py
admin.py
models.py
tests.py
views.py
__init__.py-thiswillensurethatPythonhandlesthefolderasapackage.
admin.py-thishelpstomaketheappbemodifiableinadmininterface.
models.py-thiswillstoreallthemodelsfortheapplication.
tests.py-thishastheunittests.
views.py-thisiswheretheapplicationviewsarestored.
Nowthatwehavetheapplication“myapplication”,itisagoodtimeforustoregisteritto
theDjangoprojectwepreviouslycreated,whichis“project1”.Todothis,updatethe
INSTALLED_APPStuplelocatedinthefilesettings.pyforourproject.Thisisshown
below:
INSTALLED_APPS=(
‘django.contrib.admin’,
‘django.contrib.auth’,
‘django.contrib.contenttypes’,
‘django.contrib.sessions’,
‘django.contrib.messages’,
‘django.contrib.staticfiles’,
‘myapplication’,
)
Chapter4-TheAdminInterface
In Django, an admin is readily provided for administration purposes. This interface is
determined by the module “django.countrib”. However, you will have to import some
modules.
Forthecaseof“INSTALLED_APPS”,youshouldensurethatyouhavethefollowing:
INSTALLED_APPS=(
‘django.contrib.admin’,
‘django.contrib.auth’,
‘django.contrib.contenttypes’,
‘django.contrib.sessions’,
‘django.contrib.messages’,
‘django.contrib.staticfiles’,
‘myapplication’,
)
For“MIDDLEWARE_CLASSES”,makesurethatyouhavethefollowing:
MIDDLEWARE_CLASSES=(
‘django.contrib.sessions.middleware.SessionMiddleware’,
‘django.middleware.common.CommonMiddleware’,
‘django.middleware.csrf.CsrfViewMiddleware’,
‘django.contrib.auth.middleware.AuthenticationMiddleware’,
‘django.contrib.messages.middleware.MessageMiddleware’,
‘django.middleware.clickjacking.XFrameOptionsMiddleware’,
)
ToaccesstheAdmininterfaceandbeforelaunchingtheserver,youhavetoinitializethe
database.Thefollowingcommandcanbeusedtodothis:
$pythonmanage.pysyncdb
Theabovecommandwilltheninitializethecreationofthenecessarytablesdependingon
thetypeofdatabasethatyouareusing.TheseareverynecessaryfortheAdmininterface
toberun.YoushouldthencreatetheURLfortheAdmininterface.
Openthefile“myproject/url.py”.Youwillseesomethingthatlookslikethis:
fromdjango.conf.urlsimportpatterns,include,url
fromdjango.contribimportadmin
admin.autodiscover()
urlpatterns=patterns(”,
#Examples:
#url(r’^$’,‘project1.views.home’,name=‘home’),
#url(r’^blog/’,include(‘blog.urls’)),
url(r’^admin/’,include(admin.site.urls)),
)
Theservercanthenbestartedusingthefollowingcommand:
$pythonmanage.pyrunserver
JustaccessyouradmininterfaceatthefollowingURL:
http://127.0.0.1:8000/admin/
YouwillthenfinallyhavetheAdmininterface.Thiswillallowyoutoperformsome
administrativetasksasfarasyourprojectisconcerned.
Chapter5-CreatingViewsinDjango
AviewisjustaPythonfunctionthatwilltakearequestandthenreturnaresponseobject.
TheresponsecanbeintheformoftheHTMLcontentforyourwebpage.
Consider the example given below,which shows how a simple view can be created in
Django:
fromdjango.httpimportHttpResponse
defhello(request):
text=”””<h1>welcometomyapplication</h1>”””
returnHttpResponse(text)
Theaboveviewshouldgiveyouthemessage“welcometomyapplication”.
Whenpresentingourview,wecanmakeuseoftheMVTpattern.Supposethatwehave
thetemplate“myapplication/templates/hello.html”.Ourviewcanbecreatedasfollows:
fromdjango.shortcutsimportrender
defhello(request):
returnrender(request,“myapplication/template/hello.html”,{})
Itispossibleforustopassparameterstoourview.Thisisdemonstratedbelow:
fromdjango.httpimportHttpResponse
defhello(request,number):
text=“<h1>welcometomyapplicationnumber%s!</h1>”%number
returnHttpResponse(text)
WhenitislinkedtoaURL,thenumberwhichhasbeenpassedastheparameterwillbe
displayed.
ClassBasedViews
Theseviewsareusedforsub-classViewandthentoimplementtheHTTPmethodsthatit
cansupport.Classbasedviewscanbeimplementedasshowninthefollowingprogram:
fromdjango.httpimportHttpResponse
fromdjango.views.genericimportView
classOurView(View):
defget(self,request,*args,**kwargs):
returnHttpResponse(“Hello,there!”)
Inthistypeofview,theHTTPmethodsshouldbemappedtotheclassmethodnames.In
theaboveexample,wehaveadefinedahandlerfortheGETrequestswitha“get”method.
Justlikewehaveimplementedthefunction,the“request”willbetakenasthefirst
argument,andanHTTPresponsewillbereturned.
ListingContacts
Supposewewanttowriteaviewthatwillgiveusalistofcontactsthathavebeenstored
inadatabase.Thefollowingcodecanhelpusimplementthis:
fromdjango.views.genericimportListView
fromcontacts.modelsimportContact
classListContactView(ListView):
model=Contact
TheListViewwehavesubclassedfromismadeupofnumerousmixinsthatareexpected
toprovidesomebehavior.Acodesuchasthisgivesusalotofpowerwhileusingless
code.Wecanthenuse“model=Contact”,whichwilllistthecontactswehavestoredin
thedatabase.
DefinitionofURLs
TheconfigurationofURLinformsDjangoastohowtomatchthepathofarequesttothe
Pythoncode.DjangowilllookforURLconfigurationthathasbeendefinedas
“urlpatterns”.
WecannowaddaURLmappingforthecontactlistview.Thisisshownbelow:
fromdjango.conf.urlsimportpatterns,include,url
importcontacts.views
urlpatterns=patterns(”,
url(r’^$’,contacts.views.ListContactView.as_view(),
name=‘contacts-list’,),
)
Althoughitisnotamustforustousethe“url()”function,itisofgreatimportanceas
afterwebegintoaddmoreinformationtoourURLpattern,itwillallowustomakeuseof
namedparameters,andeverythingwillbemademuchclearer.Notethatwehaveuseda
regularexpressionasthefirstparameter.
CreationofaTemplate
NotethataURLhasalreadybeendefinedforthelistview,andwecantrythisout.Django
usuallyprovidesuswithaserverthatwecanuseduringdevelopmentforthepurposeof
testingourprojects.Thisisshownbelow:
$pythonmanage.pyrunserver
Validatingmodels…
0errorsfound
Djangoversion1.4.3,usingsettings‘addressbook.settings’
Developmentserverisrunningathttp://127.0.0.1:8000/
QuittheserverwithCONTROL-C.
Atthistime,visitingtheURL,thatis,http://localhost:8000/willgiveyouanerror:
“TemplateDoesNotExist”.
Thisisbecause,fromourcode,thesystemwasexpectingtogetaURL,butwehavenot
yetcreatedit.Wecanthengoaheadandcreateit.
ThedefaultsettingisthatDjangolooksfortemplatesintheapplicationsandthedirectory
youhavespecifiedin“settings.TEMPLATE_DIRS”.Genericviewsusuallyexpecttofind
thetemplatesinthedirectorythathasbeennamedaftertheapplication,andthemodelis
expectedtohavethemodelname.Thisisespeciallyusefulinthedistributionofareusable
application,astheconsumerisabletocreatetemplatesthatoverridethedefaults,andthey
havetobestoredinadirectorywhosenameisassociatedwiththatoftheapplication.
Inthiscase,thereisnoneedforanadditionallayer,andthatiswhywewanttospecifythe
templatethatistobeusedexplicitly.Therefore,weusethe“template_name”property.
Thatlinecanbeaddedtoourcodeasshownbelow:
fromdjango.views.genericimportListView
fromcontacts.modelsimportContact
classListContactView(ListView):
model=Contact
template_name=‘contact_list.html’
Youcanthencreateasubdirectorynamed“templates”inyour“contacts”app,andthen
createtheview“contacts_list”there.Thecodeforthisisshownbelow:
<h1>Contacts</h1>
<ul>
{%forcontactinobject_list%}
<liclass=“contact”>{{contact}}</li>
{%endfor%}
</ul>
Youcanopenthefileinyourbrowserandbeabletoseethecontactsthatyouhaveadded
toyourdatabase.
CreationoftheContacts
Sinceweneedtoaddsomecontactstoourdatabase,doingsoviatheshellwillmakethe
processtooslow.Weshouldcreateaviewthatwillhelpusdoit.Thiscanbeaddedas
shownbelow:
fromdjango.views.genericimportCreateView
fromdjango.core.urlresolversimportreverse
…
classCreateContact(CreateView):
model=Contact
template_name=‘edit_contact.html’
defget_success_url(self):
returnreverse(‘contacts-list’)
Ingenericviewsthatcarryoutformprocessing,theconceptof“successURL”isused.
Thisisusedforredirectingtheuseraftertheyhavesubmittedtheformsuccessfully.
Thecodefor“edit_contact.html”shouldbeasshownbelow:
<h1>AddContact</h1>
<formaction=”{%url“contacts-new”%}”method=“POST”>
{%csrf_token%}
<ul>
{{form.as_ul}}
</ul>
<inputid=“save_contact”type=“submit”value=“Save”/>
</form>
<ahref=”{%url“contacts-list”%}”>backtolist</a>
NotethatwehavemadeuseoftheDjangoFormforthemodel.Thisisbecausewe
specifiednoneandsoDjangocreateditforus.Thefollowinglineofcodecanbeaddedto
our“url.py”filesoastoconfiguretheURL:
url(r’^new$’,contacts.views.CreateContact.as_view(),
name=‘contacts-new’,),
OnceyouopentheURLhttp://localhost:8000/newonyourbrowser,youwillbeallowed
tocreatethecontacts.
Wecanthenaddalinkthatwillleadustothe“contacts_list.html”pageasshownbelow:
<h1>Contacts</h1>
<ul>
{%forcontactinobject_list%}
<liclass=“contact”>{{contact}}</li>
{%endfor%}
</ul>
<ahref=”{%url“contacts-new”%}”>addcontact</a>
TestingViews
InDjango,twotoolscanhelpusintestingviews:“RequestFactory”and“TestClient”.
TestClientwilltaketheURLtoberetrieved,andthenitwillresolveitaccordingtothe
URLconfigurationoftheproject.Atestrequestwillthenbecreated,andthiswillthenbe
passedthroughtheview,andaresponsewillbereturned.
TheRequestFactorymakesuseofasimilarAPI.Inthiscase,onehastospecifytheURL
thatistoberetrieved,aswellastheformdataortheparameters.However,thiswillnot
resolvetheURL,butitwillreturntheRequestobject.Theresultcanthenbepassedtothe
viewmanuallyandtheresulttested.
TestscarriedusingRequestFactoryareusuallyfastercomparedtoonescarriedoutusing
TestClient.Thismightsoundlikeasmallissue,butitisofgreatsignificancewhenyouare
carryingoutlargetests.
WeneedtodemonstratehoweachkindoftestcanbecarriedoutinDjango.Considerthe
codegivenbelow:
fromdjango.test.clientimportRequestFactory
fromdjango.test.clientimportClient
…
fromcontacts.viewsimportListContactView
…
classContactViewTests(TestCase):
“““Contactlistviewtests.”””
deftest_contacts_in_the_context(self):
client=Client()
response=client.get(‘/’)
self.assertEquals(list(response.context[‘object_list’]),[])
Contact.objects.create(f_name=‘foo’,l_name=‘bar’)
response=client.get(‘/’)
self.assertEquals(response.context[‘object_list’].count(),1)
deftest_contacts_in_the_context_request_factory(self):
factory=RequestFactory()
request=factory.get(‘/’)
response=ListContactView.as_view()(request)
self.assertEquals(list(response.context_data[‘object_list’]),[])
Contact.objects.create(first_name=‘foo’,last_name=‘bar’)
response=ListContactView.as_view()(request)
self.assertEquals(response.context_data[‘object_list’].count(),1)
IntegrationTests
Wecanuseatoolnamed“Selester”,whichisgoodforwritingtestsanddrivingabrowser.
Withthistool,automationofdifferentbrowserscanbedoneeasily,andwewillbeina
positiontointeractwiththefullappjustastheuserwoulddo.Thistoolcanbeinstalledas
follows:
$pipinstallselenium
Weneedtoimplementanumberoftestsforourviews,forthefollowingpurposes::
1.Tocreateacontactandensurethatitislisted.
2.Toensurethe“addcontact”linkisvisibleandhasbeenlinkedtothelistpage.
3.Toexercisethe“addcontact”form,fillitinandthensubmittheform.
Thisisshownbelow:
fromdjango.testimportLiveServerTestCase
fromselenium.webdriver.firefox.webdriverimportWebDriver
…
classContactIntegrationTests(LiveServerTestCase):
@classmethod
defsetUpClass(cls):
cls.selenium=WebDriver()
super(ContactIntegrationTests,cls).setUpClass()
@classmethod
deftearDownClass(cls):
cls.selenium.quit()
super(ContactIntegrationTests,cls).tearDownClass()
deftest_contact_listed(self):
#creatingatestcontact
Contact.objects.create(f_name=‘foo’,l_name=‘bar’)
#ensureitislistedas<first><last>onourlist
self.selenium.get(‘%s%s’%(self.live_server_url,‘/’))
self.assertEqual(
self.selenium.find_elements_by_css_selector(‘.contact’)[0].text,
‘foobar’
)
deftest_add_contact_linked(self):
self.selenium.get(‘%s%s’%(self.live_server_url,‘/’))
self.assert_(
self.selenium.find_element_by_link_text(‘addcontact’)
)
deftest_add_contact(self):
self.selenium.get(‘%s%s’%(self.live_server_url,‘/’))
self.selenium.find_element_by_link_text(‘addcontact’).click()
self.selenium.find_element_by_id(‘id_f_name’).send_keys(‘test’)
self.selenium.find_element_by_id(‘id_l_name’).send_keys(‘contact’)
self.selenium.find_element_by_id(‘id_email’).send_keys(‘[email protected]’)
self.selenium.find_element_by_id(“save_contact”).click()
self.assertEqual(
self.selenium.find_elements_by_css_selector(‘.contact’)[-1].text,
‘testcontact’
)
Chapter6-URLMappingOur aim is to access a view via aURL.Django provides uswith amechanism named
“URLMapping”,whichcanbeimplementedbymodifyingtheprojectfile“url.py”.The
filelookslikethis:
fromdjango.conf.urlsimportpatterns,include,url
fromdjango.contribimportadmin
admin.autodiscover()
upatterns=patterns(”,
#Examples
#url(r’^$’,‘project1.view.home’,name=‘home’),
#url(r’^blog/’,include(‘blog.urls’)),
url(r’^admin’,include(admin.site.urls)),
)
AmappingisjustatupleintheURLpatternsandisasfollows:
fromdjango.conf.urlsimportpatterns,include,url
fromdjango.contribimportadmin
admin.autodiscover()
upatterns=patterns(”,
#Examples
#url(r’^$’,‘project1.view.home’,name=‘home’),
#url(r’^blog/’,include(‘blog.urls’)),
url(r’^admin’,include(admin.site.urls)),
url(r’^hello/’,‘myapplication.views.hello’,name=‘hello’),
)
As you have noticed from the above code, there are three components associated in
mapping.Thesearethefollowing:
1. Thepattern-ThisisaregexpthatmatchestheURLthatyouareinneedofresoling
andmapping.
2. Pythonpathtoyourview-Thisisthesameaswhenoneisimportingamodule.
3. Thename-ForURLreversingtobedone,onehastousethenamedURLpatterns.
Thisiswhathasbeendoneintheaboveexamples.
OrganizationofURLs
You need to create the file “url.py” for each application that you create to be able to
organizeyourURLseffectively.Thefollowingcodecanbeusedforcreationofsuchafile
fortheapp“myapplication”:
fromdjango.conf.urlsimportpatterns,include,url
upatterns=patterns(”,url(r’^hello/’,‘myapplication.views.hello’,name=‘hello’),)
Theproject“project1/url.py”shouldthenchangetothefollowing:
fromdjango.conf.urlsimportpatterns,include,url
fromdjango.contribimportadmin
admin.autodiscover()
upatterns=patterns(”,
#Examples
#url(r’^$’,‘project1.view.home’,name=‘home’),
#url(r’^blog/’,include(‘blog.urls’)),
url(r’^admin’,include(admin.site.urls)),
url(r’^myapplication/’,include(myapplication.urls)),
)
AlloftheURLsfromtheapplication“myapplication”havebeenincluded.
Tomapanewviewtothe“myapplication/url.py”,thecodefor“myapplication/url.py”can
bechangedtothefollowing:
fromdjango.conf.urlsimportpatterns,include,url
upatterns=patterns(”,
url(r’^hello/’,‘myapplication.views.hello’,name=‘hello’),
url(r’^morning/’,‘myapplication.views.morning’,name=‘morning’),
)
Note that according to the above code, the new view is located in the
“myapplication/morning”.Thecodegivenbelowcanbeusedforrefactoringtheabove:
fromdjango.conf.urlsimportpatterns,include,url
upatterns=patterns(‘myapplication.views’,
url(r’^hello/’,‘hello’,name=‘hello’),
url(r’^morning/’,‘morning’,name=‘morning’),)
HowtosendParameterstotheViews
For us to pass parameters, we just have to capture them using the regexp in ourURL
pattern.Considertheexampleviewgivenbelow:
fromdjango.shortcutsimportrender
fromdjango.httpimportHttpResponse
defhello(request):
returnrender(request,“hello.html”,{})
defvwArticle(request,artId):
text=“DisplayingtheNumberofArticle:%s”%artId
returnHttpResponse(text)
Ouraimistomaptothe“myapplication/url.py”andwewillbeinapositiontoaccessit
via the “myapplication/url.py”. The following code has to be implemented in the file
“myapplication/url.py”:
fromdjango.conf.urlsimportpatterns,include,url
upatterns=patterns(‘myapplication.views’,
url(r’^hello/’,‘hello’,name=‘hello’),
url(r’^morning/’,‘morning’,name=‘morning’),
url(r’^article/(\d+)/’,‘vwArticle’,name=‘article’),)
Pleasenote that theorderofyourparameters is very important.Suppose thatweare in
needofalistofarticlesfromaparticularmonthoftheyear.Theviewcanbechangedto
thefollowing:
fromdjango.shortcutsimportrender
fromdjango.httpimportHttpResponse
defhello(request):
returnrender(request,“hello.html”,{})
defvwArticle(request,artId):
text=“DisplayingtheNumberofArticle:%s”%artId
returnHttpResponse(text)
defvwArticle(request,month,yr):
text=“Displayingthearticlesof:%s/%s”%(yr,month)
returnHttpResponse(text)
Thecorrespondingfile“url.py”shouldbeasfollows:
fromdjango.conf.urlsimportpatterns,include,url
upatterns=patterns(‘myapplication.views’,
url(r’^hello/’,‘hello’,name=‘hello’),
url(r’^morning/’,‘morning’,name=‘morning’),
url(r’^article/(\d+)/’,‘vwArticle’,name=‘article’),
url(r’^articles/(\d{2})/(\d{4})’,‘vwArticles’,name=‘articles’),)
Youcanthentesttheappandreverseyourparametersandobservewhathappens.Inmy
case,Igotthefollowingresult:
Displayingthearticlesof:2016/11
Uponreversingtheparameters,Igotadifferentresult.However,thisisnotwhatweneed.
Topreventthis,weonlyhavetolinktheURLparametertoourviewparameter.Because
ofthat,thefile“url.py”willbeasfollows:
fromdjango.conf.urlsimportpatterns,include,url
upatterns=patterns(‘myapplication.views’,
url(r’^hello/’,‘hello’,name=‘hello’),
url(r’^morning/’,‘morning’,name=‘morning’),
url(r’^article/(\d+)/’,‘vwArticle’,name=‘article’),
url(r’^articles/(?P\d{2})/(?P\d{4})’,‘vwArticles’,name=‘articles’),)
That’sit!
Chapter7-TemplateSystem
InDjango,itispossibleforustoseparateHTMLandPython.ThePythonformstheviews
whileourHTMLwillformthetemplate.Forthesetwotobelinkedtogether,wehaveto
relyontheDjangotemplatelanguageandtherenderfunction.
TheRenderFunction
Thisfunctiontakesinthreeparameters.Theseincludethefollowing:
Request-Thisisourinitialrequest.
Path to our template- This represents the path relative to the option
“TEMPLATE_DIRS”inthevariable“settings.py”oftheproject.
Dictionaryofparameters-Thisisadictionarythathasallofthevariablesthatare
containedinatemplate.Youcanchoosetodeclareitoryoucanuse“locals()”for
thepurposeofpassingallthelocalvariablesthathavebeendeclaredintheview.
DjangoTemplateLanguage(DTL)
ThetemplateengineforDjangoprovidesyouwithamini-languagefor thedefinitionof
theuser-facinglayerofyourapplication.
HowtoDisplayVariables
InDjango,avariablelookslikethis:
{{variable}}
The templateworksby replacing theabovewith thenameof thevariable thathasbeen
passedbyourviewasourthirdparameterofthefunction“render”.Supposethatweneed
ourfile“hello.html”todisplaythecurrentdate.Todoso,thefilecanbemodifiedtothe
following:
<html>
<body>
Hellothere!!!<p>Todayison{{day}}</p>
</body>
</html>
Theviewshouldalsobechangedtothefollowing:
defhello(request):
day=datetime.datetime.now().date()
returnrender(request,“hello.html”,{“today”:day})
Youcan then try toaccess the file“URL/myapplication/hello”andyouwillobserve the
followingresult:
Hellothere!!!
TodayisonNov.11,2016
That’sit.Asmostofyoumighthavenoticed,incaseaparticularvariableisnotastring
buttheDjangoneedstodisplayit,itusesthemethod“__str__”.Withthisprinciple,one
canaccessanattributeofanobjectinthesameway.
Filters
Filtersareusefulastheycanassistyoutodisplayvariablesduringthedisplaytime.They
haveastructurewhichlookslikethis:
{{var|filters}}
Considerthefiltersgivenbelow:
{{string|truncatewords:70}}-With this filter, a string will be truncated, meaning
thatyouwillonlyseethefirst70words.
{{string|lower}}-Thisfilterwillconvertastringtolowercase.
{{string|escape|linebreaks}}-Thiswillescapethecontentsofastring,andconvert
yourlinebreaksintotags.
Itisalsopossibletosetthedefaultforaparticularvariable.
Tags
Withtags,youcanperformoperationssuchasforloop,ifcondition,templateinheritance
andothers.
Tagif
InDjango,youcanusethevariousversionsofthe“if”statementasitisdoneinPython.
Thisisshowninthecodegivenbelow:
<html>
<body>
Hellothere!!!<p>Todayison{{day}}</p>
Weareon
{%ifday.day==1%}
thefirstdayofthemonth.
{%elifday==30%}
thelastdayofthemonth.
{%else%}
Iamnotaware.
{%endif%}
</body>
</html>
Inthetemplategivenabove,thecurrentdatewillbedisplayed.
Tagfor
Thistagworksinthesamewayasthe“for”inPython.Wenowneedtochangethehello
viewsothatitcantransmitalisttothetemplate.Thisisshownbelow:
defhello(request):
day=datetime.datetime.now().date()
days=[‘Mon’,‘Tue’,‘Wed’,‘Thu’,‘Fri’,‘Sat’,‘Sun’]
returnrender(request,“hello.html”,{“today”:day,“days_of_week”:days})
Hereisthetemplateforusingthetagfordisplayingthelist:
<html>
<body>
Hellothere!!!<p>Todayison{{day}}</p>
Weareon
{%ifday.day==1%}
thefirstdayofthemonth.
{%elifday==30%}
thelastdayofthemonth.
{%else%}
Iamnotaware.
{%endif%}
<p>
{%fordaysindays_of_week%}
{{day}}
</p>
{%endfor%}
</body>
</html>
Theabovecodeshouldgiveusthedaysoftheweekaswehavespecified,togetherwith
themessagesthatwehavespecified.
BlockandExtendTags
A template system is not complete without the template inheritance. This means that
duringtheprocessofdevelopmentofatemplate,weshouldhavethemaintemplatewith
loopholesandthechildtemplatesshouldbedesignedtofillthoseloopholesaccordingto
whatthedeveloperneeds.Thisworksthroughthesamemechanisminwhichapagecan
needaspecialcssforaparticulartab.
Considerthecodegivenbelowforthetemplate“main.html”:
<html>
<head>
<title>
{%blocktitle%}PageTitle{%endblock%}
</title>
</head>
<body>
{%blockcontent%}
ContentoftheBody
{%endblock%}
</body>
</html>
Ouraimistochangethetemplate“hello.html”sothatitinheritsfromthetemplategiven
above.Hereisthecodeforthistemplate:
{%extends“main.html”%}
{%blocktitle%}TheHelloPage{%endblock%}
{%blockcontent%}
Hellothere!!!<p>Todayison{{day}}</p>
Weareon
{%ifday.day==1%}
thefirstdayofthemonth.
{%elifday==30%}
thelastdayofthemonth.
{%else%}
Iamnotaware.
{%endif%}
<p>
{%fordaysindays_of_week%}
{{days}}
</p>
{%endfor%}
{%endblock%}
Chapter8-Models
ModelsareaclassthatisusedforrepresentationofacollectionofatableinaDB.Inthis
case,eachoftheattributeofaclassisafieldinthecollectionortable.InDjango,models
aredefinedinthefile“app/models.py”.
HowtocreateaModel
Considertheexamplegivenbelow:
fromdjango.dbimportmodels
classDreamreal(models.Model):
web=models.CharField(max_length=40)
mail=models.CharField(max_length=40)
name=models.CharField(max_length=40)
phnumber=models.IntegerField()
classMeta:
db_table=“dreamreal”
Each model has to inherit from the class “django.db.models.Model”. Note that in the
aboveclass,wehavedefined4attributesthatwillformthefieldsforourtable.
Once themodelhasbeencreated, theDjango should thengenerateour actualdatabase.
Thefollowingcodecanbeused:
$pythonmanage.pysyncdb
ManipulatingData(CRUD)
ItispossibleforustoperformCRUDoperationsonourmodels.Considerthecodegiven
belowfor“myapplication/views.py”:
frommyapplication.modelsimportDreamreal
fromdjango.httpimportHttpResponse
defcrudops(request):
#Creatingtheentry
dreal=Dreamreal(
web=“www.mywebsite.com”,mail=“[email protected]”,
name=“john”,phnumber=“0725626821”
)
dreal.save()
#ReadingALLtheentries
objects=Dreamreal.objects.all()
res=‘PrintingalltheDreamrealentriesinourDB:<br>’
foreinobjects:
res+=e.name+”<br>”
#Readingaspecificentry:
john=Dreamreal.objects.get(name=“john”)
res+=‘Printingasingleentry<br>’
res+=john.name
#Deletetheentry
res+=‘<br>Deletingtheentry<br>’
john.delete()
#Update
dreal=Dreamreal(
web=“www.mywebsite.com”,mail=“[email protected]”,
name=“john”,phnumber=“0725626821”
)
dreal.save()
res+=‘Updatingtheentry<br>’
dreal=Dreamreal.objects.get(name=‘john’)
dreal.name=‘joel’
dreal.save()
returnHttpResponse(res)
OtherDataManipulations
There are also some other types of manipulations that can be done on models. The
previousCRUDoperationswereperformedontheinstancesofourmodel.However,we
donotneedtoperformouroperationsdirectlyontheclassthatrepresentsourmodel.
Wewant tocreateaview“datamanip” in thefile“myapplication/views.py”.Here is the
codefordoingthis:
frommyapplication.modelsimportDreamreal
fromdjango.httpimportHttpResponse
defdatamanip(request):
res=”
#Filteringthedata:
qs=Dreamreal.objects.filter(name=“john”)
res+=“Found:%sresults<br>”%len(qs)
#Orderingtheresults
qs=Dreamreal.objects.order_by(“name”)
foreinqs:
res+=e.name+‘<br>’
returnHttpResponse(res)
LinkingModels
There are 3ways inDjangobywhichmodels can be linked together.The firstmethod
involvestheuseof the“one-to-many”relationship.Forus todefine therelationship,we
havetousethe“django.db.models.ForeignKey”.Thisisshowninthecodegivenbelow:
fromdjango.dbimportmodels
classDreamreal(models.Model):
web=models.CharField(max_length=40)
mail=models.CharField(max_length=40)
name=models.CharField(max_length=40)
phnumber=models.IntegerField()
online=models.ForeignKey(‘Online’,default=1)
classMeta:
db_table=“dreal”
classOnline(models.Model):
domain=models.CharField(max_length=20)
classMeta:
db_table=“onlineTable”
Chapter9-PageRedirection
Thispropertyisveryusefulinwebapps.Sometimes,somethingmightoccurandtheuser
mayneedtoberedirectedtoanotherpage.Thisiswhatpageredirectionisusefulfor.To
achieveredirectioninDjango,weusethe“redirect”method.ThismethodtakestheURL
ofredirectionastheparameter.
Considerthecodegivenbelowforthefile“myapplication/views”:
defhello(request):
day=datetime.datetime.now().date()
dWeek=[‘Monday’,‘Tuesday’,‘Wednesday’,‘Thursday’,‘Friday’,‘Saturday’,‘Sunday’]
returnrender(request,“hello.html”,{“today”:day,“days_of_week”:dWeek})
defvwArticle(request,artId):
”””AviewfordisplayinganarticlebasedontheID”””
text=“DisplayingtheNumberofthearticle:%s”%artId
returnHttpResponse(text)
defvwArticles(request,year,month):
text=“Displayingthearticlesof:%s/%s”%(year,month)
returnHttpResponse(text)
Wenowneedtoredirectthe“hello”viewtothe“myproject.com”andthe“vwArticle” to
be redirected to the internal “/myapplication/articles”. The code for
“myapplication/view.py”willhavetobechangedtothefollowing:
fromdjango.shortcutsimportrender,redirect
fromdjango.httpimportHttpResponse
importdatetime
#Creatingyourownviewshere.
defhello(request):
day=datetime.datetime.now().date()
dWeek=[‘Monday’,‘Tuesday’,‘Wednesday’,‘Thursday’,‘Friday’,‘Saturday’,‘Sunday’]
returnredirect(“https://www.myproject.com”)
defvwArticle(request,artId):
”””AviewfordisplayinganarticlebasedontheID”””
text=“DisplayingtheNumberofthearticle:%s”%artId
returnredirect(vwArticles,year=“2050”,month=“02”)
defvwArticles(request,year,month):
text=“Displayingthearticlesof:%s/%s”%(year,month)
returnHttpResponse(text)
Theredirectpropertycanalsobespecifiedtobeeitherpermanentortemporary.Although
theusersmayseethisasbeingnegligible,itisimportantasthesearchengineswilluseit
forthepurposeofrankingyourwebsite.
The“name”parameterwasalsodefinedinthefile“url.py”duringtheprocessofmapping
oftheURLsasshownbelow:
url(r’^articles/(?P\d{2})/(?P\d{4})/’,‘vwArticles’,name=‘articles’),
Thenamecanbeusedasanargumentforthepurposeofredirection,andthe“vwArticle”
canbechangedfromthefollowing:
defvwArticle(request,articleId):
”””AviewfordisplayinganarticlebasedontheID”””
text=“DisplayingtheNumberofthearticle:%s”%artId
returnredirect(vwArticles,year=“2050”,month=“02”)
Tothefollowing:
defvwArticle(request,artId):
”””AviewfordisplayinganarticlebasedontheID”””
text=“DisplayingtheNumberofthearticle:%s”%artId
returnredirect(articles,year=“2050”,month=“02”)
Chapter10-SendingE-mails
DjangocomeswithaninbuiltengineforthepurposeofsendingE-mails.TosendtheE-
mails,youhave to import the“smtplib”, similar towhathappens inPython. InDjango,
onehas to import theclass“django.core.mail”.Theparameters for thefile“settings.py”
alsohavetobechanged.Theseparametersaregivenbelow:
EMAIL_HOST–Thesmtpserver.
EMAIL_HOST_USER–Thelogincredentialsforyoursmtpserver.
EMAIL_HOST_PASSWORD–Thepasswordcredentialsforyoursmtpserver.
EMAIL_PORT–Thesmtpserverport.
EMAIL_USE_TLSor_SSL−Trueifthesecureconnectionisused.
Considertheviewgivenbelow,whichisasimpledemonstrationofhowonecansendan
E-mail:
fromdjango.core.mailimportsend_mail
fromdjango.httpimportHttpResponse
defsendEmail(request,emailto):
res=send_mail(“hellojohn”,“Werehaveyoulost?”,“[email protected]”,[emailto])
returnHttpResponse(‘%s’%res)
Belowaretheparametersofthemethod“send_mail”:
subject–TheE-mailsubject.
message–TheE-mailbody.
from_email–TheE-mailfrom.
recipient_list–Alistofthereceivers’E-mailaddresses.
fail_silently−Boolean,iffalse,thesend_mailwillgiveanexceptionincaseofan
error.
auth_user−Userloginifnotsetinthe“settings.py”.
auth_password−Theuserpasswordifnotsetinthe“settings.py”.
connection–TheE-mailbackend.
html_message−Ifpresent,ourE-mailwillbeamultipart/alternative.
ThefollowingURLcanbeusedforthepurposeofaccessingourview:
fromdjango.conf.urlsimportpatterns,url
upatterns=paterns(‘myapplication.views’,url(r’^email/(?P<emailto>
[\w.%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4})/’,
‘sendEmail’,name=‘sendEmail’),)
Using“send_mass_mail”tosendE-mail
When thismethod has been used, wewill get the number ofmessages that have beendeliveredsuccessfully.Itissimilartoourpreviousmethod,butittakesanextraparameter.Considerthecodegivenbelow:
fromdjango.core.mailimportsend_mass_mail
fromdjango.httpimportHttpResponse
defsendEmail(request,emailto):
message1=(‘subject1’,‘message1’,‘[email protected]’,[emailto1])
message2=(‘subject2’,‘message2’,‘[email protected]’,[emailto2])
res=send_mail((message1,message2),fail_silently=False)
returnHttpResponse(‘%s’%res)
ThefollowingURLcanbeusedforaccessingtheview:
fromdjango.conf.urlsimportpatterns,url
upatterns=paterns(‘myapplication.views’,url(r’^massEmail/(?P<emailto1>
[\w.%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4})/(?P<emailto2>
[\w.%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4})’,‘sendEmail’,name=‘sendEmail’),)
Thefollowingaretheparametersforthemethod:
datatuples−Atupleinwhicheachelementwillbelike“subject,message,
from_email,recipient_list”.
fail_silently−Boolean,ifsetto“false”,send_mailwillgiveanexceptionincasean
erroroccurs.
auth_user–Auserloginifithasnotbeensetin“settings.py”.
auth_password–Theuserpasswordifithasnotbeensetinthe“settings.py”.
connection–TheE-mailbackend.
ThecodehasbeenusedforsendingtwoE-mails.
Again,inourcode,wehaveusedthe“Pythonsmtpdebuggingserver”andthefollowing
commandcanbeusedforlaunchingit:
$python-msmtpd-n-cDebuggingServerlocalhost:1025
TheabovecodemeansthattheE-mailsthataresentwillbeprintedonthe“stdout”and
yourdummyserverisbeingexecutedontheportnumber1025.
Sometimes,wemightneedtosendthemailstoadministratorsandmanagers.Inthiscase,
wecanusethemethods“mail_admins”and“mail_managers” respectively.Thesettings
for these are defined in the file “settings.py”. Let’s assume that the following are the
settingsforouroption:
ADMINS=((‘john’,‘[email protected]’),)
MANAGERS=((‘joel’,‘[email protected]’),)
fromdjango.core.mailimportmail_admins
fromdjango.httpimportHttpResponse
defAdminsEmail(request):
res=mail_admins(‘mysubject’,‘UserInterfaceistiresome.’)
returnHttpResponse(‘%s’%res)
Withtheabovecode,anE-mailwillbesendtoalloftheadministratorswhoarecontained
inthe“ADMINS”section.Considerthecodegivenbelow:
fromdjango.core.mailimportmail_managers
fromdjango.httpimportHttpResponse
defManagersEmail(request):
res=mail_managers(‘mysubject’,‘Correctsomespellingerrorsonyoursite.’)
returnHttpResponse(‘%s’%res)
With the above code, an E-mail will be send to all of the managers defined in the
“MANAGERS”section.
Thefollowingarethedetailsofourparameters:
Subject–TheE-mailsubject.
message–TheE-mailbody.
fail_silently–ABoolean,ifsetto“false”“send_mail”willgiveanexceptionifan
erroroccurs.
connection–TheE-mailbackend.
html_message−ifit’spresent,oure-mailwillbeamultipart/alternative.
SendingHTMLE-mail
Considerthecodegivenbelow,whichdemonstrateshowthiscanbedone:
fromdjango.core.mailimportsend_mail
fromdjango.httpimportHttpResponse
res=send_mail(“hellojohn”,“wherehaveyoulost?”,“[email protected]”,
[“[email protected]”],html_message=”)
Theabovecodewillgiveoutamultipart/alternativeE-mail.Wewanttocreateaviewthat
willbeusedforsendinganHTMLE-mail:
fromdjango.core.mailimportEmailMessage
fromdjango.httpimportHttpResponse
defhTMLEmail(request,emailto):
html_cont=“<strong>Wherehaveyoulost?</strong>”
email=EmailMessage(“mysubject”,html_cont,“[email protected]”,[emailto])
email.content_subtype=“html”
res=email.send()
returnHttpResponse(‘%s’%res)
Thefollowingaretheparametersofthemessage:
Subject–TheE-mailsubject.
message–TheE-mailbodyinHTML.
from_email–TheE-mailfrom.
to−Listofourreceivers’E-mailaddresses.
bcc−Listofthe“Bcc”receivers’ofE-mailaddresses.
connection–TheE-mailbackend.
ThefollowingisaURLthatcanbeusedforaccessingourview:
fromdjango.conf.urlsimportpatterns,url
upatterns=paterns(‘myapplication.views’,url(r’^htmlemail/(?P<emailto>
[\w.%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4})/’,
‘hTMLEmail’,name=‘hTMLEmail’),)
HowtoSendEmailswithAttachment
Forus todo this,wehave touse the“attach”method in theobject“EmailMesage”. A
viewforsendinganE-mailwithanattachmentcanbeimplementedasshownbelow:
fromdjango.core.mailimportEmailMessage
fromdjango.httpimportHttpResponse
defemailWithAttach(request,emailto):
html_cont=“Wherehaveyoulost?”
email=EmailMessage(“mysubject”,html_content,“[email protected]”,emailto])
email.content_subtype=“html”
fd=open(‘manage.py’,‘r’)
email.attach(‘manage.py’,fd.read(),‘text/plain’)
res=email.send()
returnHttpResponse(‘%s’%res)
Thefollowingisadescriptionoftheusedparameters:
filename−Nameofourfiletoattach.
content−Contentofourfiletoattach.
mimetype−Contentmimetypeoftheattachment.
Chapter11-GenericViews
Insomecases,itbecomesdifficultforustowriteviewsaswehavedoneintheprevious
examples.Supposethatyouareinneedofastaticpage.GenericviewsinDjangoprovide
us with a mechanism for how to set views in a simple manner. These can be seen as
classes rather than as functions, which is the case with classic views. The classes for
GenericviewsinDjangocanbefoundintheclass“django.views.generic”.
To view the available generic classes, which are over 10, the following steps are
necessary:
>>>importdjango.views.generic
>>>dir(django.views.generic)
[‘ArchiveIndexView’,‘CreateView’,‘DateDetailView’,‘DayArchiveView’,
‘DeleteView’,‘DetailView’,‘FormView’,‘GenericViewError’,‘ListView’,
‘MonthArchiveView’,‘RedirectView’,‘TemplateView’,‘TodayArchiveView’,
‘UpdateView’,‘View’,‘WeekArchiveView’,‘YearArchiveView’,‘__builtins__’,
‘__doc__’,‘__file__’,‘__name__’,‘__package__’,‘__path__’,‘base’,‘dates’,
‘detail’,‘edit’,‘list’]
StaticPages
Weneedtopublishastaticpagefromthetemplate“static.html”.Hereisthecodeforthe
file“static.html”:
<html>
<body>
Astaticpagesample!!!
</body>
</html>
For this to be done as we learned before, the file “myapplication/views.py” has to be
changedtothefollowing:
fromdjango.shortcutsimportrender
defstatic(request):
returnrender(request,‘static.html’,{})
Andthefile“myapplication/urls.py”hastobechangedtothefollowing:
fromdjango.conf.urlsimportpatterns,url
upatterns=patterns(“myapplication.views”,url(r’^static/’,‘static’,name=‘static’),)
This can be solved effectively by use of the generic views. In this case, the file
“myapplication/views.py”willbeasfollows:
fromdjango.views.genericimportTemplateView
classStaticView(TemplateView):
template_name=“static.html”
Andthefile“myapplication/urls.py”shouldbeasfollows:
frommyapplication.viewsimportStaticView
fromdjango.conf.urlsimportpatterns
upatterns=patterns(“myapplication.views”,(r’^static/$’,StaticView.as_view()),)
Alternatively,wecanachievethisbychangingthefile“url.py”andmakingnochangeto
thefile“views.py”.Thisisshownbelow:
fromdjango.views.genericimportTemplateView
fromdjango.conf.urlsimportpatterns,url
upatterns=patterns(“myapplication.views”,
url(r’^static/’,TemplateView.as_view(template_name=‘static.html’)),)
As shown in the above code, only the file “url.py” has been changed in the second
method.
ListingandDisplayingDatafromtheDB
Nowweneed to listourentries in theDreamrealmodel.Thegenericviewclassnamed
“ListView”makesthiseasyforustodo.Youjusthavetoeditthefile“url.py”andupdate
ittogetthefollowing:
fromdjango.views.genericimportListView
fromdjango.conf.urlsimportpatterns,url
upatterns=patterns(
“myapplication.views”,url(r’^dreamreals/’,ListView.as_view(model=Dreamreal,
template_name=”list.html”)),
)
Thefile“url.py”shouldnowbecomeasshownbelow:
fromdjango.views.genericimportListView
fromdjango.conf.urlsimportpatterns,url
upatterns=patterns(“myapplication.views”,
url(r’^dreamreals/’,ListView.as_view(
template_name=”list.html”)),
model=Dreamreal,context_object_name=”dreamreals_objects”,)
Theassociatedtemplateshouldbeasshownbelow:
{%extends”template.html”%}
{%blockcontent%}
Dreamreals:<p>
{%fordinobject_list%}
{{d.name}}</p>
{%endfor%}
{%endblock%}
Chapter12-FormProcessinginDjango
CreationofformsinDjangoisdoneinasimilarwaytocreatingmodels.Wejusthaveto
inheritfromourDjangoclassandtheformfieldswillbeourclassattributes.First,adda
filenamed“forms.py”inthefoldernamed“myapplication”.Thisfilewillholdourforms.
Wewilldemonstratethisbycreatingaloginform:
#-*-coding:utf-8-*-
fromdjangoimportforms
classMyForm(forms.Form):
user=forms.CharField(max_length=80)
pwd=forms.CharField(widget=forms.PasswordInput())
Inourcase,ourpasswordwillbehiddenandthatiswhywehaveusedtheabovewidget.
There are a number ofwidgets inDjango that you canmake use ofwhenever you are
creatingyourforms.
HowtouseaForminaView
“GET”and“POST”arethetwotypesofHTTPrequests.TherequestobjectinDjangothat
is passed as aparameter as aviewhas an attributenamed“method”.This iswhere the
typeof request is set. ,The request canbeused for accessing all the data that has been
passedtothePOST.
Theloginviewcanbecreatedasfollows:
#-*-coding:utf-8-*-
frommyapplication.formsimportLoginForm
deflogin(request):
username=“notyetloggedin”
ifrequest.method==“POST”:
#Gettingthepostedform
LoginForm=MyForm(request.POST)
ifLoginForm.is_valid():
username=LoginForm.cleaned_data[‘username’]
else:
LoginForm=Myform()
returnrender(request,‘loggedin.html’,{“username”:username})
Our view will display the result of our login form, which has been posted via the
“loggedin.html”.Forthepurposeoftesting,theloginformtemplateisneeded.Thiscanbe
called“login.html”.Itisshownbelow:
<html>
<body>
<formname=“form”action=“{%url“myapplication.views.login”%}”
method=“POST”>{%csrf_token%}
<divstyle=“max-width:460px;”>
<center>
<inputtype=“text”style=“margin-left:19%;”
placeholder=“Username”name=“username”/>
</center>
</div>
<br>
<divstyle=“max-width:460px;”>
<center>
<inputtype=“password”style=“margin-left:19%;”
placeholder=“password”name=“password”/>
</center>
</div>
<br>
<divstyle=“max-width:460px;”>
<center>
<buttonstyle=“border:0px;background-color:#4285F4;margin-top:9%;
height:36px;width:79%;margin-left:20%;”type=“submit”
value=“Login”>
<strong>Login</strong>
</button>
</center>
</div>
</form>
</body>
</html>
Our templatewill showa login formand thenpost the result to a loginviewas shown
above.Youmighthavenoticedthetagusedinthetemplate,whichwillworktopreventa
“Cross-siteRequestForgery(CSRF)”attackonoursite.
{%csrf_token%}
Now that we are having our “Lofin.html” template, we need to have the template
“loggedin.html”andthiswillberenderedaftertheformhasbeentreated.Thisisshown
below:
<html>
<body>
Yourusernameis:<strong>{{username}}</strong>
</body>
</html>
OnlythepairoftheURLsisremainingforustogetstarted.Theseshouldbedefinedin
thefile“myapplication/urls.py”asshownbelow:
fromdjango.conf.urlsimportpatterns,url
fromdjango.views.genericimportTemplateView
upatterns=patterns(‘myapplication.views’,
url(r’^connection/’,TemplateView.as_view(template_name=‘login.html’)),
url(r’^login/’,‘login’,name=‘login’))
FormValidation
Ourformcanbevalidatedbyuseofthemethodgivenbelow:
MyForm.is_valid()
Thatisself-validationenginefortheDjango.Thiswillensurethatourfieldsarerequired.
Wenowwanttomakesurethatauserwhologsintothesystemispresentinthedatabase.
Forthistobedone,thefile“myapplication/forms.py”hastobechangedtothefollowing:
#-*-coding:utf-8-*-
fromdjangoimportforms
frommyapplication.modelsimportDreamreal
classMyForm(forms.Form):
user=forms.CharField(max_length=90)
pwd=forms.CharField(widget=forms.PasswordInput())
defclean_message(self):
username=self.cleaned_data.get(“username”)
user=Dreamreal.objects.filter(name=username)
ifnotuser:
raiseforms.ValidationError(“Userisnotinourdb!”)
returnusername
Once themethod “is_valid” has been called and the user has been found to be in the
database,wewillgetthebestoutput.
Chapter13-UploadingFiles
Our web apps should be in a position to support uploading of files. The files can be
pictures,pdfs,worddocuments,songsandothertypes.
UploadinganImage
BeforecanstarttoworkwithimagesinDjango,youhavetoensurethatyouhaveinstalled
thePythonImageLibrary(PIL).Todemonstratehowimagescanbeuploaded,letusbegin
bycreatingaprofileform.Thefollowingcodeisnecessaryforthis:
#-*-coding:utf-8-*-
fromdjangoimportforms
classProfForm(forms.Form):
name=forms.CharField(max_length=90)
pict=forms.ImageFields()
The“ImageField”workstoensurethatthefilethatisuploadedisanimage.Ifthisisnot
thecase,thenvalidationoftheformwillfail.
We now need to create a model named “Profile”, which will be used for storing the
images that we upload. This has to be done in the file “myapplication/models.py” as
showninthecodegivenbelow:
fromdjango.dbimportmodels
classProfiles(models.Model):
name=models.CharField(max_length=60)
pic=models.ImageField(upload_to=‘pictures’)
classMeta:
db_table=“profiles”
As shown in the above code, the “ImageField” has taken a compulsory field named
“upload_to”.Thispropertyrepresentsthelocationinourharddriveinwhichwewillstore
ouruploadedimages.
Now that we have the model and the form, the view can be created in the directory
“myapplication/views.py”.Thisisshownbelow:
#-*-coding:utf-8-*-
frommyapplication.formsimportProfileForm
frommyapplication.modelsimportProfile
defSvProfile(request):
saved=False
ifrequest.method==“POST”:
#Gettingourpostedform
MyProfForm=ProfileForm(request.POST,request.FILES)
ifMyProfForm.is_valid():
prof=Profile()
prof.name=MyProfForm.cleaned_data[“name”]
prof.picture=MyProfForm.cleaned_data[“picture”]
prof.save()
saved=True
else:
MyProfForm=Profform()
returnrender(request,‘saved.html’,locals())
Hereisthecodeforthefile“myapplication/templates/saved.html”:
<html>
<body>
{%ifsaved%}
<strong>Theprofilepicturewassuccessfullysaved.</strong>
{%endif%}
{%ifnotsaved%}
<strong>Theprofilewasnotsaved.</strong>
{%endif%}
</body>
</html>
Hereisthecodeforthefile“myapplication/templates/profile.html”
<html>
<body>
<formname=“form”enctype=“multipart/form-data”
action=“{%url“myapplication.views.SvProfile”%}”method=“POST”>{%
csrf_token%}
<divstyle=“max-width:460px;”>
<center>
<inputtype=“text”style=“margin-left:19%;”
placeholder=“Name”name=“name”/>
</center>
</div>
<br>
<divstyle=“max-width:460px;”>
<center>
<inputtype=“file”style=“margin-left:19%;”
placeholder=“Picture”name=“picture”/>
</center>
</div>
<br>
<divstyle=“max-width:460px;”>
<center>
<buttonstyle=“border:1px;background-color:#4285F4;margin-top:9%;
height:36px;width:79%;margin-left:20%;”type=“submit”value=“Login”>
<strong>Login</strong>
</button>
</center>
</div>
</form>
</body>
</html>
WhatweneednextistosetupourURLsandthenwewillbeinapositiontogetstarted.
Thecodegivenbelowcanbeusedforspecificationofthese:
fromdjango.conf.urlsimportpatterns,url
fromdjango.views.genericimportTemplateView
upatterns=patterns(
‘myapplication.views’,url(r’^profile/’,TemplateView.as_view(
template_name=‘profile.html’)),url(r’^saved/’,‘SvProfile’,name=‘saved’)
)
Nowweshouldbe inaposition toupload images toourwebapp.However,whenyou
needtouploadanothertypeoffile,the“ImageField”hastobereplacedwith“FileField”
inboththeFormandtheModel.
Chapter14-HandlingCookies
Sometimes,wemight need ourweb app to store information about each visitor to our
website.Notethatcookieswillalwaysbestoredontheclientsideofourwebappandthey
mayworkornotwork.
Let’s demonstrate how cookies work in Django by creating a login app as we did
previously.Theappwilllogyouinforanumberofminutesandoncethetimehasexpired,
youwillbeloggedoutoftheapp.Forthispurpose,twocookieshavetobesetup.These
includethe“username”and“last_connection”.Theloginviewhastobechangedtothe
following:
fromdjango.templateimportRequestContext
deflogin(request):
username=“notyetloggedin”
ifrequest.method==“POST”:
#Gettingourpostedform
MyForm=LoginForm(request.POST)
ifMyForm.is_valid():
username=MyForm.cleaned_data[‘username’]
else:
MyForm=LoginForm()
response=render_to_response(request,‘loggedin.html’,{“username”:username},
context_instance=RequestContext(request))
response.set_cookie(‘last_connection’,datetime.datetime.now())
response.set_cookie(‘username’,datetime.datetime.now())
returnresponse
Themethod“set_cookie”isusedforthepurposeofsettingcookiesasshownintheabove
code.Thevaluesforallofourcookieshavetobereturnedasastring.
It is now time for us to create a “fmView” for our login form, so the formwill not be
displayedifthecookiehasbeensetandisnomorethan5secondsold.Thisisshownin
thecodegivenbelow:
deffmView(request):
if‘username’inrequest.COOKIESand‘last_connection’inrequest.COOKIES:
username=request.COOKIES[‘username’]
last_connection=request.COOKIES[‘last_connection’]
last_connection_time=datetime.datetime.strptime(last_connection[:-7],
“%Y-%m-%d%H:%M:%S”)
if(datetime.datetime.now()-last_connection_time).seconds<5:
returnrender(request,‘loggedin.html’,{“username”:username})
else:
returnrender(request,‘login.html’,{})
else:
returnrender(request,‘login.html’,{})
Asshowninthecodegivenbelow,forustoaccessthecookiethathasbeenused,weuse
the“COOKIESattribute(dict)”ofourrequest.NowwemustchangetheURLinthefile
“url.py”sothatitmatcheswiththecurrentview.Thisisshownbelow:
fromdjango.conf.urlsimportpatterns,url
fromdjango.views.genericimportTemplateView
upatterns=patterns(‘myapplication.views’,
url(r’^connection/’,‘formView’,name=‘loginform’),
url(r’^login/’,‘login’,name=‘login’))
TestingCookies
The“request”objectinDjangoprovidesuswithsomemethodsthatcanhelpusintesting
ofcookies.Examplesofsuchmethodsinclude:“set_test_cookie()”,
“test_cookie_worked()”and“delete_test_cookie()”.Inoneofyourviews,youare
expectedtocreateacookie,andthentestitinanotherview.Totestcookies,youneedtwo
cookies,asyouwillhavetowaitandseeiftheclienthasacceptedthecookiefromthe
server.
Intheviewyoucreatedpreviously,addthefollowingline:
request.session.set_test_cookie()
Itisagoodideatoensurethatthislineisexecuted.Setitasthefirstlineintheviewand
ensurethatitisoutsideanyconditionalblock.Inthesecondview,addthefollowingcode
atthetoptoensurethatitisexecuted:
ifrequest.session.test_cookie_worked():
print“>>>>TESTCOOKIEHASWORKED!”
request.session.delete_test_cookie()
ClientSideCookies
Nowthatyouaresurethatcookieswork,youneedtoimplementasitevisitcounterby
makingtheconceptofcookies.Toachievethis,youwillhavetoimplementtwocookies:
onethatwillbeusedforkeepingtrackofthenumberoftimesthatauservisitsthe
website,andanothercookiefortrackingthelasttimethattheuservisitedthesite.
Thefollowingcodebestdemonstratesthis:
defindex(request):
context=RequestContext(request)
category_list=Category.objects.all()
context_dict={‘categories’:category_list}
forcategoryincategory_list:
category.url=encode_url(category.name)
page_list=Page.objects.order_by(‘-views’)[:5]
context_dict[‘pages’]=page_list
####NEWCODE####
#ObtaintheResponseobjectearlysoastoaddthecookieinformation.
response=render_to_response(‘myfolder/index.html’,context_dict,context)
#Getnumberofvisitstooursite.
#UsetheCOOKIES.get()functionforobtainingthevisitscookie.
#Incasethecookieexists,thereturnedvaluewillbecastedtoaninteger.
#Ifthecookiedoesnotexist,wewilldefaulttozeroandthencastthat.
visits=int(request.COOKIES.get(‘visits’,‘0’))
#Doyoufindthelast_visitcookie?
if‘last_visit’inrequest.COOKIES:
#Yesitexists!Getthevalueofthecookie.
last_visit=request.COOKIES[‘last_visit’]
#Castingourvaluetoadate/timeobjectinPython.
last_visit_time=datetime.strptime(last_visit[:-7],“%Y-%m-%d%H:%M:%S”)
#Ifithasbeenmorethanonedaysincetheuser’slastvisit…
if(datetime.now()-last_visit_time).days>0:
#…reassignitsvalueto+1ofwhichitwasbefore…
response.set_cookie(‘visits’,visits+1)
#…andthenupdatethelastvisitcookie,also.
response.set_cookie(‘last_visit’,datetime.now())
else:
#Cookielast_visitdoesnotexist,somakeittoyourcurrentdate/time.
response.set_cookie(‘last_visit’,datetime.now())
#Returntheresponsebacktouser,andupdateanycookiesthatneedchanging.
returnresponse
####ENDNEWCODE####
Asyoumayhavenoticed,themajorityoftheabovecodeisforcheckingthecurrentdate
andtime.Thiscanonlyworkafterwehaveincludedthe“datetime”moduleforPython.
Todothis,justaddthefollowingimportstatementatthetopofyourcode:
fromdatetimeimportdatetime
Chapter15-SessionsinDjango
Sessionsareusedfor thepurposeofhandlingcookiesandimprovingthesecurityofour
webapp.Theyabstracthowcookiesarereceivedandsent.
SettingupCookies
InDjango, sessions canbe enabled in the file “settings.py”, and some lines have to be
addedbetween the“MIDDLEWARE_CLASSES” and “INSTALLED_APPS”.This should
be done when the project is being created. You should be aware that the
“MIDDLE_WARE”classesshouldhavethefollowing:
‘django.contrib.sessions.middleware.SessionMiddleware’
Andthe“INSTALLED_APPS”shouldhavethefollowing:
‘django.contrib.sessions’
Weshouldnowchangetheloginviewtosavetheserversideofourusernamecookie.This
isshowninthecodegivenbelow:
deflogin(request):
username=‘notloggedin’
ifrequest.method==‘POST’:
MyForm=LoginForm(request.POST)
ifMyLoginForm.is_valid():
username=MyForm.cleaned_data[‘username’]
request.session[‘username’]=username
else:
MyForm=LoginForm()
returnrender(request,‘loggedin.html’,{“username”:username}
We can then create the view “fmView”, and the formwill not be displayed in case the
cookiehasbeenset.Thisisshowninthecodegivenbelow:
deffmView(request):
ifrequest.session.has_key(‘username’):
username=request.session[‘username’]
returnrender(request,‘loggedin.html’,{“username”:username})
else:
returnrender(request,‘login.html’,{})
Weshouldnowchangethefile“url.py”sothatitcanmatchthenewviewwehave.Thisis
shownbelow:
fromdjango.conf.urlsimportpatterns,url
fromdjango.views.genericimportTemplateView
upatterns=patterns(‘myapplication.views’,
url(r’^connection/’,‘formView’,name=‘loginform’),
url(r’^login/’,‘login’,name=‘login’))
Thefollowingisalogoutviewthatwillworktodeleteourcookie:
deflogout(request):
try:
delrequest.session[‘username’]
except:
pass
returnHttpResponse(“<strong>Youhavebeenloggedout.</strong>”)
ThiscanbepairedwithalogoutURLinthefile“myapplication/url.py”asshownbelow:
url(r’^logout/’,‘logout’,name=‘logout’),
Thefollowingareotherusefulactionsassociatedwithsessions:
set_expiry(value)–Forsettingtheexpirationtimeofthesession.
get_expiry_age()–Forreturningthenumberofthesecondsuntilthesession
expires.
get_expiry_date()–Forreturningthedatethatthesessionwillexpire.
clear_expired()–Forremovingtheexpiredsessionsfromoursessionstore.
get_expire_at_browser_close()–Forreturningeither“True”or“False”,as
determinedbywhetherthesessioncookieshadexpiredduringthetimeofclosing
thebrowser.
SessionData
Tobemoresecure,itisrecommendedthatwestoreoursessiondataontheserverside.
ThesessionIDcookiethathasbeenstoredontheclientsidecanbeusedforthepurpose
ofunlockingthedata.Theexamplegivenbelowbestdemonstrateshowthiscanbedone:
defindex(request):
context=RequestContext(request)
category_list=Category.objects.all()
context_dict={‘categories’:category_list}
forcategoryincategory_list:
category.url=encode_url(category.name)
page_list=Page.objects.order_by(‘-views’)[:5]
context_dict[‘pages’]=page_list
####NEWCODE####
ifrequest.session.get(‘last_visit’):
#Thesessionhasthevalueforlastvisit
last_visit_time=request.session.get(‘last_visit’)
visits=request.session.get(‘visits’,0)
if(datetime.now()-datetime.strptime(last_visit_time[:-7],“%Y-%m-%d%H:%M:%S”)).days>0:
request.session[‘visits’]=visits+1
request.session[‘last_visit’]=str(datetime.now())
else:
#ThegetwillreturnNone,asthesessiondoesn’thaveavalueforuser’slastvisit.
request.session[‘last_visit’]=str(datetime.now())
request.session[‘visits’]=1
###
#ENDNEWCODE####
#Renderandthenreturnrenderedresponsebacktouser.
returnrender_to_response(‘myfolder/index.html’,context_dict,context)
Itisrecommendedthatyoudeletetheclient-sidecookiesbeforeyoubegintomakeuseof
thesession-baseddata.Youshoulddothisfromthebrowser’sdevelopertoolsanddelete
eachofthecookiesindividually.Youcanalsochoosetoentirelyclearthecacheforyour
browser.
Chapter16-MemoryCachinginDjango
Caching isused to save the resultof anexpensiveoperation so that there isnoneed to
perform the operation again if its result is needed in the future. The pseudocode given
belowdemonstrateshowcachingisdone:
givenaURL,trytofindthepageinthecache
ifpageisfoundincache:
returnthecachedpage
else:
generatethepage
savethegeneratedpageinacache
returnthegeneratedpage
Djangohasaninbuiltcachingsystemthatenablesitsuserstostoretheirdynamicpages.
Thiswillmeanthattheywillnothavetocalculatethemagainiftheyneedthem.Djangois
goodatthis,becausetheusercancachethefollowing:
Theoutputofspecificview.
Apartofthetemplate.
Theentiresite.
ForDjangodeveloperstousethecache,theyfirsthavetospecifywherethecachewillbe
stored.There are numerous possibilities for this as the cache can be stored inmemory,
databaseoronfilesystem.Forthistobeset,onehastoeditthefile“settings.py”forthe
project.
HowtosetupCacheinDatabase
Addthefollowingcodetothefile“settings.py”oftheproject:
CACHES={
‘default’:{
‘BACKEND’:‘django.core.cache.backends.db.DatabaseCache’,
‘LOCATION’:‘table_name’,
}
}
For the setting to be completed, we have to create a cache table and give it the name
“table_name”.
HowtoSetUptheCacheinMemory
Thisisthemosteffectivewaytosetupthecache.However,itisdeterminedbythePython
BindingLibrary thatyouareusing foryourmemorycache.The implementationcanbe
doneasshownbelow:
CACHES={
‘default’:{
‘BACKEND’:‘django.core.cache.backends.memcached.MemcachedCache’,
‘LOCATION’:‘127.0.0.1:12344’,
}
}
Or
CACHES={
‘default’:{
‘BACKEND’:‘django.core.cache.backends.memcached.MemcachedCache’,
‘LOCATION’:‘unix:/tmp/memcached.sock’,
}
}
HowtoCachetheEntireSite
This is the simplest way that caching can be done inDjango. For this to be done, the
option“MIDDLEWARE_CLASSES”hastobeeditedinthefile“settings.py”.Considerthe
codegivenbelow,whichshowswhathastobeaddedtothesection:
MIDDLEWARE_CLASSES+=(
‘django.middleware.cache.UpdateCacheMiddleware’,
‘django.middleware.common.CommonMiddleware’,
‘django.middleware.cache.FetchFromCacheMiddleware’,
)
Note that the above should be implemented in the given order as if not done thatway,
errorswilloccur.
Thefollowingalsoneedtobesetinthesamefile:
CACHE_MIDDLEWARE_ALIAS–cachealiastobeusedforthestorage.
CACHE_MIDDLEWARE_SECONDS–numberofsecondsthateachpageshouldbecached.
CachingaView
For thosewho don’t need to cache an entire site, they can choose to cache parts of an
entiresite.Thiscanbedonethroughtheuseofadecoratornamed“cache_page”,which
comesinbuilt inDjango.Supposeweneedtocachetheresultof theview“vwArticles”.
Thiscanbedoneasshownbelow:
fromdjango.views.decorators.cacheimportcache_page
@cache_page(60*15)
defvwArticles(request,year,month):
text=“Displayingthearticlesof:%s/%s”%(year,month)
returnHttpResponse(text)
Theviewgivenabovewasmaptothefollowing:
upatterns=patterns(‘myapplication.views’,
url(r’^articles/(?P<month>\d{2})/(?P<year>\d{4})/’,‘vwArticles’,name=‘articles’),)
CachingaTemplateFragment
Onecanalsodecide tocatchpartsof a fragment.The“cache” tagcanbeused for this
purpose.Thetemplate“hello.html”isasshownbelow:
{%extends“template.html”%}
{%blocktitle%}HelloPage{%endblock%}
{%blockcontent%}
Hellothere!!!<p>Todayison{{day}}</p>
Weareon
{%ifday.day==1%}
thefirstdayofthemonth.
{%elifday==30%}
thelastdayofthemonth.
{%else%}
Iamnotaware.
{%endif%}
<p>
{%fortodayindays_of_week%}
{{day}}
</p>
{%endfor%}
{%endblock%}
Forustocachethecontentblock,thetemplatewillbeasfollows:
{%loadcache%}
{%extends”template.html”%}
{%blocktitle%}HelloPage{%endblock%}
{%cache500content%}
{%blockcontent%}
Hellothere!!!<p>Todayison{{day}}</p>
Weareon
{%ifday.day==1%}
thefirstdayofthemonth.
{%elifday==30%}
thelastdayofthemonth.
{%else%}
Iamnotaware.
{%endif%}
<p>
{%fortodayindays_of_week%}
{{today}}
</p>
{%endfor%}
{%endblock%}
{%endcache%}
Conclusion
We have come to the conclusion of the guide. Django is a very useful framework of
Python that lets us develop web applications in an easy and quick manner. Before
beginning touse this framework fordevelopmentofwebapps, youhave to ensure that
youhaveinstalledPythonitself,adatabasesystemandaswellashavingsetupaserver.
Fromthere,youcanbegintodevelopyourwebappsusingallthehelpfulinformationin
thisbook.