本文介紹 django.http.Http404
的用法。
聲明
class django.http.Http404
當您返回諸如
之類的錯誤時,您有責任定義生成的錯誤頁麵的 HTML:HttpResponseNotFound
return HttpResponseNotFound('<h1>Page not found</h1>')
為方便起見,並且因為在您的站點上擁有一致的 404 錯誤頁麵是一個好主意,Django 提供了 Http404
異常。如果您在視圖函數中的任何位置引發Http404
,Django 將捕獲它並為您的應用程序返回標準錯誤頁麵,以及 HTTP 錯誤代碼 404。
示例用法:
from django.http import Http404
from django.shortcuts import render
from polls.models import Poll
def detail(request, poll_id):
try:
p = Poll.objects.get(pk=poll_id)
except Poll.DoesNotExist:
raise Http404("Poll does not exist")
return render(request, 'polls/detail.html', {'poll': p})
為了在 Django 返回 404 時顯示自定義 HTML,您可以創建一個名為 404.html
的 HTML 模板並將其放在模板樹的頂層。當
設置為 DEBUG
False
時,將提供此模板。
當
為 DEBUG
True
時,您可以向 Http404
提供消息,它將出現在標準的 404 調試模板中。將這些消息用於調試目的;它們通常不適合在生產 404 模板中使用。
相關用法
- Python Django HttpRequest.accepts用法及代碼示例
- Python Django HttpRequest.headers用法及代碼示例
- Python Django HttpRequest.get_signed_cookie用法及代碼示例
- Python Django HttpRequest.user用法及代碼示例
- Python Django HttpRequest.method用法及代碼示例
- Python Django HttpRequest.__iter__用法及代碼示例
- Python Django HttpRequest.build_absolute_uri用法及代碼示例
- Python calendar HTMLCalendar formatmonth()用法及代碼示例
- Python HTMLCalendar formatyearpage()用法及代碼示例
- Python calendar HTMLCalendar formatyear()用法及代碼示例
- Python HTMLCalendar formatyear()用法及代碼示例
- Python HTMLCalendar formatmonth()用法及代碼示例
- Python HTML轉Markdown用法及代碼示例
- Python calendar HTMLCalendar formatyearpage()用法及代碼示例
- Python cudf.core.column.string.StringMethods.is_vowel用法及代碼示例
- Python torch.distributed.rpc.rpc_async用法及代碼示例
- Python torch.nn.InstanceNorm3d用法及代碼示例
- Python sklearn.cluster.MiniBatchKMeans用法及代碼示例
- Python pandas.arrays.IntervalArray.is_empty用法及代碼示例
- Python tf.compat.v1.distributions.Multinomial.stddev用法及代碼示例
- Python numpy.less()用法及代碼示例
- Python Matplotlib.figure.Figure.add_gridspec()用法及代碼示例
- Python tf.compat.v1.distribute.MirroredStrategy.experimental_distribute_dataset用法及代碼示例
- Python Django File.save用法及代碼示例
- Python Sympy Permutation.list()用法及代碼示例
注:本文由純淨天空篩選整理自djangoproject.com大神的英文原創作品 django.http.Http404。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。