Opened 11 years ago

Closed 11 years ago

Last modified 11 years ago

#21769 closed Bug (invalid)

Error message displayed falsely in poll tutorial

Reported by: timdaman Owned by: nobody
Component: Documentation Version: 1.6
Severity: Normal Keywords: tutorial
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: yes UI/UX: no

Description

I am working through the tutorial "poll" project and found a very minor bug in the example code. In section 4,

https://docs.djangoproject.com/en/1.6/intro/tutorial04/

the vote method erroneously displays the error message when the vote form is initially loaded. This does not make sense since the user has not yet attempted to submit form data. In a real world setting this could cause user confusion and frustration as "Looking at a blank form" is != to "Submitting a blank form" and the messages each requires is different ("Please make a choice" vs. "Oops, you forgot to make a choice").

Below is the modification I made to detect this difference and display the correct output. I am new to django and my last web editing job was in the 90's so I welcome suggestions for improvements of my code!

def vote(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)

    if request.method == "POST":
        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,)))
    else:
        return render(request, 'polls/detail.html', {
            'poll': p,
        })

Change History (2)

comment:1 by Claude Paroz, 11 years ago

Resolution: invalid
Status: newclosed

The vote view in the tutorial is only meant to be used as the form action url, not for the initial display. The initial display of the poll is handled by the detail view on part 3 of the tutorial. The except path in the vote view is there to prevent the view from crashing if it is inadvertently called by a GET method, but it should generally not happen.

comment:2 by timdaman, 11 years ago

Ah ha, I see what you mean. Oops, sorry about that.

Note: See TracTickets for help on using tickets.
Back to Top