Boston Python Workshop/Saturday/Web app project: Difference between revisions

imported>Paulproteus
imported>Paulproteus
Line 609:
 
== Part 3: Let people vote ==
 
=== Write a simple form ===
 
Let’s update our poll detail template (“polls/detail.html”) from the last tutorial so that the template contains an HTML <form> element:
 
<pre>
<h1>{{ poll.question }}</h1>
 
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
 
<form action="/polls/{{ poll.id }}/vote/" method="post">
{% csrf_token %}
{% for choice in poll.choice_set.all %}
<input type="radio" name="choice" value="{{ choice.id }}" />
<label>{{ choice.choice }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>
</pre>
 
There is a lot going on there. A quick rundown:
 
* The above template displays a radio button for each poll choice. The value of each radio button is the associated poll choice's ID. The name of each radio button is "choice". That means, when somebody selects one of the radio buttons and submits the form, the form submission will represent the Python dictionary {'choice': '3'}. That's the basics of HTML forms; you can learn more about them.
* We set the form's action to /polls/{{ poll.id }}/vote/, and we set method="post". Normal web pages are requested using ''GET'', but the standards for HTTP indicate that if you are changing data on the server, you must use the ''POST'' method. (Whenever you create a form that alters data server-side, use method="post". This tip isn't specific to Django; it's just good Web development practice.)
* Since we're creating a POST form (which can have the effect of modifying data), we need to worry about Cross Site Request Forgeries. Thankfully, you don't have to worry too hard, because Django comes with a very easy-to-use system for protecting against it. In short, all POST forms that are targeted at internal URLs should use the {% csrf_token %} template tag.
 
The {% csrf_token %} tag requires information from the request object, which is not normally accessible from within the template context. To fix this, a small adjustment needs to be made to the detail view, so that it looks like the following:
 
<pre>
from django.template import RequestContext
# ...
def detail(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
return render_to_response('polls/detail.html', {'poll': p},
context_instance=RequestContext(request))
</pre>
 
The details of how this works are explained in the documentation for RequestContext.
 
Now, let's create a Django view that handles the submitted data and does something with it. Remember, in Tutorial 3, we created a URLconf for the polls application that includes this line:
 
(r'^(?P<poll_id>\d+)/vote/$', 'vote'),
 
We also created a dummy implementation of the vote() function. Let's create a real version. Add the following to polls/views.py:
 
from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.template import RequestContext
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_to_response('polls/detail.html', {
'poll': p,
'error_message': "You didn't select a choice.",
}, context_instance=RequestContext(request))
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.views.results', args=(p.id,)))
 
This code includes a few things we haven't covered yet in this tutorial:
 
* request.POST is a dictionary-like object that lets you access submitted data by key name. In this case, request.POST['choice'] returns the ID of the selected choice, as a string. request.POST values are always strings.
* Note that Django also provides request.GET for accessing GET data in the same way -- but we're explicitly using request.POST in our code, to ensure that data is only altered via a POST call.
* request.POST['choice'] will raise KeyError if choice wasn't provided in POST data. The above code checks for KeyError and redisplays the poll form with an error message if choice isn't given.
* After incrementing the choice count, the code returns an HttpResponseRedirect rather than a normal HttpResponse. HttpResponseRedirect takes a single argument: the URL to which the user will be redirected (see the following point for how we construct the URL in this case).
 
As the Python comment above points out, you should always return an HttpResponseRedirect after successfully dealing with POST data. This tip isn't specific to Django; it's just good Web development practice. That way, if the web surfer hits ''reload'', they get the success page again, rather than re-doing the action.
 
 
We are using the reverse() function in the HttpResponseRedirect 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 the variable portion of the URL pattern that points to that view. In this case, using the URLconf we set up in Tutorial 3, this reverse() call will return a string like
 
'/polls/3/results/'
 
... where the 3 is the value of p.id. This redirected URL will then call the 'results' view to display the final page. Note that you need to use the full name of the view here (including the prefix).
 
After somebody votes in a poll, the vote() view redirects to the results page for the poll. Let's write that view:
 
def results(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
return render_to_response('polls/results.html', {'poll': p})
 
This is almost exactly the same as the detail() view from Tutorial 3. The only difference is the template name. We'll fix this redundancy later.
 
Now, create a results.html template:
 
<pre>
<h1>{{ poll.question }}</h1>
 
<ul>
{% for choice in poll.choice_set.all %}
<li>{{ choice.choice }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>
 
<a href="/polls/{{ poll.id }}/">Vote again?</a>
</pre>
 
Now, go to /polls/1/ in your browser and vote in the poll. You should see a results page that gets updated each time you vote. If you submit the form without having chosen a choice, you should see the error message.
 
Does it work?! If so, show your neighbor!
 
== Part 3.5: Deploy again! ==
Anonymous user