簡體   English   中英

Django - 使用自定義模板處理所有異常

[英]Django - Handle all exceptions with custom templates

我希望能夠拋出任何狀態代碼的異常。 我有這個模板結構

templates
|---error
|   |----401.html
|   |----403.html
|   |----404.html
|   |----451.html
|   |----500.html

有沒有辦法引發這樣的異常: raise Error("Not available here!", status_code=451)這將自動顯示templates/error/451.html模板? 並且當發生服務器錯誤時,應呈現templates/error/500.html

我嘗試使用handler401handler500並引發自定義異常但沒有任何效果...

# exceptions.py
class HttpResponseNotAuthenticated(HttpResponse):
    status_code = 401


# views.py
def pseudo_view():
    return HttpResponseNotAuthenticated("Please login")

錯誤是用 Django 開箱即用的,我猜這就是你說“沒有任何作用”時所指的

您需要像這樣覆蓋此功能: https : //docs.djangoproject.com/en/3.0/topics/http/views/#customizing-error-views

指定在您的 URLconf 中看到的處理程序(將它們設置在其他任何地方將不起作用)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM