Else Statement Without an If Django Tutorial

Hi everyone,

I’m working through the django tutorial and I noticed a part in chapter 4 which is confusing me quite a bit. The following code block shows an “else” statement with no “if” associated with it. I’m aware of this behavior when using a for loop in vanilla python but this doesn’t look to be the case here. Can someone please help explain a little further what is going on behind the scenes here?

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse

from .models import Choice, Question


# ...
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,)))

This is standard Python.

From the Python docs at 8. Errors and Exceptions — Python 3.12.1 documentation

The tryexcept statement has an optional else clause , which, when present, must follow all except clauses . It is useful for code that must be executed if the try clause does not raise an exception.

(There’s more there that you can read, including some example code using this feature.)

1 Like

Ken,

That behavior totally slipped my mind. Thank you for the clarification!