Writing your first Django app, part 4¶
This tutorial begins whereTutorial 3 left off. We’recontinuing the web-poll application and will focus on form processing andcutting down our code.
Where to get help:
If you’re having trouble going through this tutorial, please head over totheGetting Help section of the FAQ.
Write a minimal form¶
Let’s update our poll detail template (“polls/detail.html”) from the lasttutorial, so that the template contains an HTML<form>
element:
polls/templates/polls/detail.html
¶<formaction="{%url'polls:vote'question.id%}"method="post">{%csrf_token%}<fieldset><legend><h1>{{question.question_text}}</h1></legend>{%iferror_message%}<p><strong>{{error_message}}</strong></p>{%endif%}{%forchoiceinquestion.choice_set.all%}<inputtype="radio"name="choice"id="choice{{forloop.counter}}"value="{{choice.id}}"><labelfor="choice{{forloop.counter}}">{{choice.choice_text}}</label><br>{%endfor%}</fieldset><inputtype="submit"value="Vote"></form>
A quick rundown:
- The above template displays a radio button for each question choice. The
value
of each radio button is the associated question choice’s ID. Thename
of each radio button is"choice"
. That means, when somebodyselects one of the radio buttons and submits the form, it’ll send thePOST datachoice=#
where # is the ID of the selected choice. This is thebasic concept of HTML forms. - We set the form’s
action
to{%url'polls:vote'question.id%}
, and wesetmethod="post"
. Usingmethod="post"
(as opposed tomethod="get"
) is very important, because the act of submitting thisform will alter data server-side. Whenever you create a form that altersdata server-side, usemethod="post"
. This tip isn’t specific toDjango; it’s good web development practice in general. forloop.counter
indicates how many times thefor
tag has gonethrough its loop- Since we’re creating a POST form (which can have the effect of modifyingdata), we need to worry about Cross Site Request Forgeries.Thankfully, you don’t have to worry too hard, because Django comes with ahelpful system for protecting against it. In short, all POST forms that aretargeted at internal URLs should use the
{%csrf_token%}
template tag.
Now, let’s create a Django view that handles the submitted data and doessomething with it. Remember, inTutorial 3, wecreated a URLconf for the polls application that includes this line:
polls/urls.py
¶path("<int:question_id>/vote/",views.vote,name="vote"),
We also created a dummy implementation of thevote()
function. Let’screate a real version. Add the following topolls/views.py
:
polls/views.py
¶fromdjango.httpimportHttpResponse,HttpResponseRedirectfromdjango.shortcutsimportget_object_or_404,renderfromdjango.urlsimportreversefrom.modelsimportChoice,Question# ...defvote(request,question_id):question=get_object_or_404(Question,pk=question_id)try:selected_choice=question.choice_set.get(pk=request.POST["choice"])except(KeyError,Choice.DoesNotExist):# Redisplay the question voting form.returnrender(request,"polls/detail.html",{"question":question,"error_message":"You didn't select a choice.",},)else:selected_choice.votes+=1selected_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.returnHttpResponseRedirect(reverse("polls:results",args=(question.id,)))
This code includes a few things we haven’t covered yet in this tutorial:
request.POST
is a dictionary-likeobject that lets you access submitted data by key name. In this case,request.POST['choice']
returns the ID of the selected choice, as astring.request.POST
values arealways strings.Note that Django also provides
request.GET
for accessing GET data in the same way –but we’re explicitly usingrequest.POST
in our code, to ensure that data is onlyaltered via a POST call.request.POST['choice']
will raiseKeyError
ifchoice
wasn’t provided in POST data. The above code checks forKeyError
and redisplays the question form with an errormessage ifchoice
isn’t given.After incrementing the choice count, the code returns an
HttpResponseRedirect
rather than a normalHttpResponse
.HttpResponseRedirect
takes a single argument: theURL to which the user will be redirected (see the following point for howwe construct the URL in this case).As the Python comment above points out, you should always return an
HttpResponseRedirect
after successfully dealing withPOST data. This tip isn’t specific to Django; it’s good web developmentpractice in general.We are using the
reverse()
function in theHttpResponseRedirect
constructor in this example.This function helps avoid having to hardcode a URL in the view function.It is given the name of the view that we want to pass control to and thevariable portion of the URL pattern that points to that view. In thiscase, using the URLconf we set up inTutorial 3,thisreverse()
call will return a string like"/polls/3/results/"
where the
3
is the value ofquestion.id
. This redirected URL willthen call the'results'
view to display the final page.
As mentioned inTutorial 3,request
is anHttpRequest
object. For more onHttpRequest
objects, see therequest andresponse documentation.
After somebody votes in a question, thevote()
view redirects to the resultspage for the question. Let’s write that view:
polls/views.py
¶fromdjango.shortcutsimportget_object_or_404,renderdefresults(request,question_id):question=get_object_or_404(Question,pk=question_id)returnrender(request,"polls/results.html",{"question":question})
This is almost exactly the same as thedetail()
view fromTutorial 3. The only difference is the template name. We’ll fix thisredundancy later.
Now, create apolls/results.html
template:
polls/templates/polls/results.html
¶<h1>{{question.question_text}}</h1><ul>{%forchoiceinquestion.choice_set.all%}<li>{{choice.choice_text}} --{{choice.votes}} vote{{choice.votes|pluralize}}</li>{%endfor%}</ul><ahref="{%url'polls:detail'question.id%}">Vote again?</a>
Now, go to/polls/1/
in your browser and vote in the question. You should see aresults page that gets updated each time you vote. If you submit the formwithout having chosen a choice, you should see the error message.
Note
The code for ourvote()
view does have a small problem. It first getstheselected_choice
object from the database, then computes the newvalue ofvotes
, and then saves it back to the database. If two users ofyour website try to vote atexactly the same time, this might go wrong:The same value, let’s say 42, will be retrieved forvotes
. Then, forboth users the new value of 43 is computed and saved, but 44 would be theexpected value.
This is called arace condition. If you are interested, you can readAvoiding race conditions using F() to learn how you can solve thisissue.
Use generic views: Less code is better¶
Thedetail()
(fromTutorial 3) andresults()
views are very short – and, as mentioned above, redundant. Theindex()
view, which displays a list of polls, is similar.
These views represent a common case of basic web development: getting data fromthe database according to a parameter passed in the URL, loading a template andreturning the rendered template. Because this is so common, Django provides ashortcut, called the “generic views” system.
Generic views abstract common patterns to the point where you don’t even need towrite Python code to write an app. For example, theListView
andDetailView
generic viewsabstract the concepts of “display a list of objects” and“display a detail page for a particular type of object” respectively.
Let’s convert our poll app to use the generic views system, so we can delete abunch of our own code. We’ll have to take a few steps to make the conversion.We will:
- Convert the URLconf.
- Delete some of the old, unneeded views.
- Introduce new views based on Django’s generic views.
Read on for details.
Why the code-shuffle?
Generally, when writing a Django app, you’ll evaluate whether generic viewsare a good fit for your problem, and you’ll use them from the beginning,rather than refactoring your code halfway through. But this tutorialintentionally has focused on writing the views “the hard way” until now, tofocus on core concepts.
You should know basic math before you start using a calculator.
Amend URLconf¶
First, open thepolls/urls.py
URLconf and change it like so:
polls/urls.py
¶fromdjango.urlsimportpathfrom.importviewsapp_name="polls"urlpatterns=[path("",views.IndexView.as_view(),name="index"),path("<int:pk>/",views.DetailView.as_view(),name="detail"),path("<int:pk>/results/",views.ResultsView.as_view(),name="results"),path("<int:question_id>/vote/",views.vote,name="vote"),]
Note that the name of the matched pattern in the path strings of the second andthird patterns has changed from<question_id>
to<pk>
. This isnecessary because we’ll use theDetailView
generic view to replace ourdetail()
andresults()
views, and it expects the primary key valuecaptured from the URL to be called"pk"
.
Amend views¶
Next, we’re going to remove our oldindex
,detail
, andresults
views and use Django’s generic views instead. To do so, open thepolls/views.py
file and change it like so:
polls/views.py
¶fromdjango.httpimportHttpResponseRedirectfromdjango.shortcutsimportget_object_or_404,renderfromdjango.urlsimportreversefromdjango.viewsimportgenericfrom.modelsimportChoice,QuestionclassIndexView(generic.ListView):template_name="polls/index.html"context_object_name="latest_question_list"defget_queryset(self):"""Return the last five published questions."""returnQuestion.objects.order_by("-pub_date")[:5]classDetailView(generic.DetailView):model=Questiontemplate_name="polls/detail.html"classResultsView(generic.DetailView):model=Questiontemplate_name="polls/results.html"defvote(request,question_id):...# same as above, no changes needed.
Each generic view needs to know what model it will be acting upon. This isprovided using either themodel
attribute (in this example,model=Question
forDetailView
andResultsView
) or by defining theget_queryset()
method (asshown inIndexView
).
By default, theDetailView
genericview uses a template called<appname>/<modelname>_detail.html
.In our case, it would use the template"polls/question_detail.html"
. Thetemplate_name
attribute is used to tell Django to use a specifictemplate name instead of the autogenerated default template name. Wealso specify thetemplate_name
for theresults
list view –this ensures that the results view and the detail view have adifferent appearance when rendered, even though they’re both aDetailView
behind the scenes.
Similarly, theListView
genericview uses a default template called<appname>/<modelname>_list.html
; we usetemplate_name
to tellListView
to use our existing"polls/index.html"
template.
In previous parts of the tutorial, the templates have been providedwith a context that contains thequestion
andlatest_question_list
context variables. ForDetailView
thequestion
variable is providedautomatically – since we’re using a Django model (Question
), Djangois able to determine an appropriate name for the context variable.However, for ListView, the automatically generated context variable isquestion_list
. To override this we provide thecontext_object_name
attribute, specifying that we want to uselatest_question_list
instead.As an alternative approach, you could change your templates to matchthe new default context variables – but it’s a lot easier to tell Django touse the variable you want.
Run the server, and use your new polling app based on generic views.
For full details on generic views, see thegeneric views documentation.
When you’re comfortable with forms and generic views, readpart 5 of thistutorial to learn about testing our polls app.