Last active
October 20, 2021 00:54
-
-
Save Marceloromeugoncalves/4436219d10248cd579ff556a32b29bf7 to your computer and use it in GitHub Desktop.
Raising a 404 error - Django
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
É 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.