Skip to content

Instantly share code, notes, and snippets.

@Marceloromeugoncalves
Last active October 20, 2021 00:54
Show Gist options
  • Save Marceloromeugoncalves/4436219d10248cd579ff556a32b29bf7 to your computer and use it in GitHub Desktop.
Save Marceloromeugoncalves/4436219d10248cd579ff556a32b29bf7 to your computer and use it in GitHub Desktop.
Raising a 404 error - Django
#Raising a 404 error
#polls/views.py
from django.http import Http404
from django.shortcuts import render
from .models import Question
#...
def detail(request, question_id):
try:
question = Question.objects.get(pk=question_id)
except Question.DoesNotExist:
raise Http404('Question does not exist')
return render(request, 'polls/detail.html', {'question': question})
#Uma maneira mais elegante de de fazer a mesma coisa.
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from django.http import HttpResponse
from django.http import Http404
from .models import Question
#...
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/detail.html', {'question': question})
@Marceloromeugoncalves
Copy link
Author

Marceloromeugoncalves commented Sep 29, 2021

Ao tentar acessar um objeto Question que não existe uma exceção Http404 será lançada com a mensagem que definirmos no construtor da classe Http404.

image

É importante observar que a mensagem acima está detalhada porque estamos utilizando a configuração DEBUG=True no arquivo de configuração do projeto settings.py.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment