Tuesday, November 5, 2019

PollOpinion site in Django-6 ( Making pages for the PollSite)

In this post we'll work with Choice model and vote functionality. We begin with modifying the polls/templates/polls/detail.html file as shown below:

<h1>{{ question.question_text }}</h1>

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
    <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
    <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br>
{% endfor %}
<input type="submit" value="Vote">
</form>

In the above code-

1. We display a radio button for each question choice. The value of each radio button is the associated question 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, it’ll send the POST data choice=# where # is the ID of the selected choice.

2. We set the form’s action to {% url 'polls:vote' question.id %}, and we set method="post". Using method="post" (as opposed to method="get") is very important, because the act of submitting this form will alter data server-side. Whenever you create a form that alters data server-side, use method="post".

3. forloop.counter indicates how many times the for tag has gone through its loop.

4. All POST forms that are targeted at internal URLs should use the {% csrf_token %} template tag for protecting against  Cross Site Request Forgeries.

Next we'll create a Django view that handles the submitted data and provides some functionality. Open the polls/views.py file and modify it with the code as shown below:

def vote(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.
return render(request, 'polls/detail.html', {'question': question,'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=(question.id,)))

Let's explore the above code to understand the functionality:

1. The request.POST is a dictionary-like object that lets us access submitted data by key name. Thus, request.POST['choice'] returns the ID of the selected choice, as a string.

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.

2. The request.POST['choice'] will raise KeyError if choice wasn’t provided in POST data. The above code checks for KeyError and re-displays the question form with an error message if choice isn’t given.

3. 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. We should always return an HttpResponseRedirect after successfully dealing with POST data.

4. 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 previous post, this reverse() call will return a string like '/polls/3/results/'  where the 3 is the value of question.id. This redirected URL will then call the 'results' view to display the final page.

As seen from the last line of the vote()

return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) 

after the voting is done for a question the vote() view redirects to the results page for the question. Let’s write that view in the  polls/views.py:

def results(request, question_id):

question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/results.html', {'question': question})

To display the poll results we need to implement the results.html which will be created in the polls/templates/polls/results.html directory:

<h1>{{ question.question_text }}</h1>

<ul>
{% for choice in question.choice_set.all %}
    <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>

<a href="{% url 'polls:detail' question.id %}">Vote again?</a>

Now let's open http://127.0.0.1:8000/ and take a poll:


To take poll click on the link and chose the answer and click vote:



Notice that the results page that gets updated each time we vote. If we submit the form without having chosen a choice, we should see the error message:










Share:

0 comments:

Post a Comment