Search code examples
pythondjangohttp-status-code-404

Raising Http404 in Django


I have the following path:

path("polls/<int:week_id>/vote/", views.vote, name="vote")

And in my view, I wrote the following method:

def vote(request, week_id):
  week = Week.objects.get(pk=week_id)
  try:
    selected_choice = week.choice_set.get(pk=request.POST["choice"])
  except Week.DoesNotExist:
    raise Http404("Poll for said week does not exists")
  else:
    selected_choice.votes += 1
    selected_choice.save()
    return redirect("results", week_id)

I'm trying to raise an 404 page if a user navigates to polls/123/vote, where 123 is a non-existing week in the database. For some reason the code above returns a DoesNotExist error instead of the actual 404 page. I'm assuming that line of code were i'm raising the 404 page is not being hit. Is that right?


Solution

  • You need to move week down into the try block:

    def vote(request, week_id):
      try:
        week = Week.objects.get(pk=week_id)
        selected_choice = week.choice_set.get(pk=request.POST["choice"])
      except Week.DoesNotExist:
        raise Http404("Poll for said week does not exists")
      else:
        selected_choice.votes += 1
        selected_choice.save()
        return redirect("results", week_id)