You are on page 1of 5

Writing your first Django app, part 4

ThistutorialbeginswhereTutorial3leftoff.WerecontinuingtheWebpollapplicationand
willfocusonsimpleformprocessingandcuttingdownourcode.
Write a simple form
Letsupdateourpolldetailtemplate(polls/detail.html)fromthelasttutorial,sothatthe
templatecontainsanHTML<form>element:
Aquickrundown:
Theabovetemplatedisplaysaradiobuttonforeachpollchoice.Thevalueofeachradio
buttonistheassociatedpollchoicesID.Thenameofeachradiobuttonis"choice".
Thatmeans,whensomebodyselectsoneoftheradiobuttonsandsubmitstheform,itll
sendthePOSTdatachoice=#where#istheIDoftheselectedchoice.Thisisthebasic
conceptofHTMLforms.
Wesettheformsactionto{% url 'polls:vote' poll.id %},andweset
method="post".Usingmethod="post"(asopposedtomethod="get")isveryimportant,
becausetheactofsubmittingthisformwillalterdataserverside.Wheneveryoucreate
aformthataltersdataserverside,usemethod="post".ThistipisntspecifictoDjango
itsjustgoodWebdevelopmentpractice.
forloop.counterindicateshowmanytimesthefortaghasgonethroughitsloop
SincewerecreatingaPOSTform(whichcanhavetheeffectofmodifyingdata),we
needtoworryaboutCrossSiteRequestForgeries.Thankfully,youdonthavetoworry
toohard,becauseDjangocomeswithaveryeasytousesystemforprotectingagainst
it.Inshort,allPOSTformsthataretargetedatinternalURLsshouldusethe
{% csrf_token %}templatetag.
Now,letscreateaDjangoviewthathandlesthesubmitteddataanddoessomethingwithit.
Remember,inTutorial3,wecreatedaURLconfforthepollsapplicationthatincludesthis
line:
url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
Wealsocreatedadummyimplementationofthevote()function.Letscreateareal
version.Addthefollowingtopolls/views.py:
<h1>{{ poll.question }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'polls:vote' poll.id %}" method="post">
{% csrf_token %}
{% for choice in poll.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br
{% endfor %}
<input type="submit" value="Vote" />
</form>
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from polls.models import Choice, Poll
# ...
def vote(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the poll voting form.
return render(request, 'polls/detail.html', {
'poll': p,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
Thiscodeincludesafewthingswehaventcoveredyetinthistutorial:
request.POSTisadictionarylikeobjectthatletsyouaccesssubmitteddatabykey
name.Inthiscase,request.POST['choice']returnstheIDoftheselectedchoice,asa
string.request.POSTvaluesarealwaysstrings.
NotethatDjangoalsoprovidesrequest.GETforaccessingGETdatainthesameway
butwereexplicitlyusingrequest.POSTinourcode,toensurethatdataisonlyaltered
viaaPOSTcall.
request.POST['choice']willraiseKeyErrorifchoicewasntprovidedinPOSTdata.
TheabovecodechecksforKeyErrorandredisplaysthepollformwithanerrormessage
ifchoiceisntgiven.
Afterincrementingthechoicecount,thecodereturnsanHttpResponseRedirectrather
thananormalHttpResponse.HttpResponseRedirecttakesasingleargument:theURL
towhichtheuserwillberedirected(seethefollowingpointforhowweconstructthe
URLinthiscase).
AsthePythoncommentabovepointsout,youshouldalwaysreturnan
HttpResponseRedirectaftersuccessfullydealingwithPOSTdata.Thistipisntspecific
toDjangoitsjustgoodWebdevelopmentpractice.
Weareusingthereverse()functionintheHttpResponseRedirectconstructorinthis
example.ThisfunctionhelpsavoidhavingtohardcodeaURLintheviewfunction.Itis
giventhenameoftheviewthatwewanttopasscontroltoandthevariableportionof
theURLpatternthatpointstothatview.Inthiscase,usingtheURLconfwesetupin
Tutorial3,thisreverse()callwillreturnastringlike
'/polls/3/results/'
...wherethe3isthevalueofp.id.ThisredirectedURLwillthencallthe'results'
viewtodisplaythefinalpage.
AsmentionedinTutorial3,requestisaHttpRequestobject.FormoreonHttpRequest
objects,seetherequestandresponsedocumentation.
Aftersomebodyvotesinapoll,thevote()viewredirectstotheresultspageforthepoll.
Letswritethatview:
from django.shortcuts import get_object_or_404, render
def results(request, poll_id):
poll = get_object_or_404(Poll, pk=poll_id)
return render(request, 'polls/results.html', {'poll': poll})
Thisisalmostexactlythesameasthedetail()viewfromTutorial3.Theonlydifferenceis
thetemplatename.Wellfixthisredundancylater.
Now,createapolls/results.htmltemplate:
Now,goto/polls/1/inyourbrowserandvoteinthepoll.Youshouldseearesultspage
thatgetsupdatedeachtimeyouvote.Ifyousubmittheformwithouthavingchosena
choice,youshouldseetheerrormessage.
Use generic views: Less code is better
Thedetail()(fromTutorial3)andresults()viewsarestupidlysimpleand,as
mentionedabove,redundant.Theindex()view(alsofromTutorial3),whichdisplaysalist
ofpolls,issimilar.
TheseviewsrepresentacommoncaseofbasicWebdevelopment:gettingdatafromthe
databaseaccordingtoaparameterpassedintheURL,loadingatemplateandreturningthe
renderedtemplate.Becausethisissocommon,Djangoprovidesashortcut,calledthe
genericviewssystem.
Genericviewsabstractcommonpatternstothepointwhereyoudontevenneedtowrite
Pythoncodetowriteanapp.
Letsconvertourpollapptousethegenericviewssystem,sowecandeleteabunchofour
owncode.Welljusthavetotakeafewstepstomaketheconversion.Wewill:
1. ConverttheURLconf.
2. Deletesomeoftheold,unneededviews.
3. IntroducenewviewsbasedonDjangosgenericviews.
Readonfordetails.
<h1>{{ poll.question }}</h1>
<ul>
{% for choice in poll.choice_set.all %}
<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize
{% endfor %}
</ul>
<a href="{% url 'polls:detail' poll.id %}">Vote again?</a>
Whythecodeshuffle?
Generally,whenwritingaDjangoapp,youllevaluatewhethergenericviewsare
agoodfitforyourproblem,andyoullusethemfromthebeginning,ratherthan
refactoringyourcodehalfwaythrough.Butthistutorialintentionallyhasfocused
onwritingtheviewsthehardwayuntilnow,tofocusoncoreconcepts.
Youshouldknowbasicmathbeforeyoustartusingacalculator.
Amend URLconf
First,openthepolls/urls.pyURLconfandchangeitlikeso:
Amend views
Next,weregoingtoremoveouroldindex,detail,andresultsviewsanduseDjangos
genericviewsinstead.Todoso,openthepolls/views.pyfileandchangeitlikeso:
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic
from polls.models import Choice, Poll
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_poll_list'
def get_queryset(self):
"""Return the last five published polls."""
return Poll.objects.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
model = Poll
template_name = 'polls/detail.html'
class ResultsView(generic.DetailView):
model = Poll
template_name = 'polls/results.html'
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns('',
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(), name='results'
url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
)
WritingyourfirstDjangoapp,part3 WritingyourfirstDjangoapp,part5
def vote(request, poll_id):
....
Wereusingtwogenericviewshere:ListViewandDetailView.Respectively,thosetwo
viewsabstracttheconceptsofdisplayalistofobjectsanddisplayadetailpagefora
particulartypeofobject.
Eachgenericviewneedstoknowwhatmodelitwillbeactingupon.Thisisprovided
usingthemodelattribute.
TheDetailViewgenericviewexpectstheprimarykeyvaluecapturedfromtheURLto
becalled"pk",sowevechangedpoll_idtopkforthegenericviews.
Bydefault,theDetailViewgenericviewusesatemplatecalled
<app name>/<model name>_detail.html.Inourcase,itwouldusethetemplate
"polls/poll_detail.html".Thetemplate_nameattributeisusedtotellDjangotousea
specifictemplatenameinsteadoftheautogenerateddefaulttemplatename.Wealsospecify
thetemplate_namefortheresultslistviewthisensuresthattheresultsviewandthe
detailviewhaveadifferentappearancewhenrendered,eventhoughtheyrebotha
DetailViewbehindthescenes.
Similarly,theListViewgenericviewusesadefaulttemplatecalled
<app name>/<model name>_list.htmlweusetemplate_nametotellListViewtouseour
existing"polls/index.html"template.
Inpreviouspartsofthetutorial,thetemplateshavebeenprovidedwithacontextthat
containsthepollandlatest_poll_listcontextvariables.ForDetailViewthepoll
variableisprovidedautomaticallysincewereusingaDjangomodel(Poll),Djangoisable
todetermineanappropriatenameforthecontextvariable.However,forListView,the
automaticallygeneratedcontextvariableispoll_list.Tooverridethisweprovidethe
context_object_nameattribute,specifyingthatwewanttouselatest_poll_listinstead.
Asanalternativeapproach,youcouldchangeyourtemplatestomatchthenewdefault
contextvariablesbutitsaloteasiertojusttellDjangotousethevariableyouwant.
Runtheserver,anduseyournewpollingappbasedongenericviews.
Forfulldetailsongenericviews,seethegenericviewsdocumentation.
Whenyourecomfortablewithformsandgenericviews,readpart5ofthistutorialtolearn
abouttestingourpollsapp.
20052014DjangoSoftwareFoundationunlessotherwisenoted.Djangoisa
registeredtrademarkoftheDjangoSoftwareFoundation.LinuxWebhosting
graciouslyprovidedbyMediaTemple.

You might also like