2013-05-03 60 views
5

我想提出404在腳本例如,不同地方的一些錯誤消息:Http404("some error msg: %s" %msg) 所以,在我的urls.py我包括:的Django提高404消息

handler404 = Custom404.as_view() 

誰能告訴我我應該如何處理我的觀點中的錯誤。我對Django相當陌生,所以一個例子會有很大的幫助。
非常感謝提前。

+2

由於您覆蓋'handler404',設計'404.html'並使用'raise Http404' – karthikr 2013-05-03 21:22:55

回答

4

一般而言,404錯誤是「找不到頁面」錯誤 - 它不應該具有可自定義的消息,僅僅因爲只有在找不到頁面時纔會引發它。

您可以設置爲404

0

默認的404處理器調用404.html狀態參數返回TemplateResponse。您可以編輯,如果你不需要任何幻想或者可以通過設置handler404視圖覆蓋404處理器 - see more here

1

您可以返回一個狀態代碼一個普通的HttpResponse對象(在這種情況下404)

from django.shortcuts import render_to_response 

def my_view(request): 
    template_context = {} 

    # ... some code that leads to a custom 404 

    return render_to_response("my_template.html", template_context, status=404) 
4

如果你想實現它,通常不應該有404錯誤埠中的任何自定義消息,你可以使用django中間件來做到這一點。

中間件

from django.http import Http404, HttpResponse 


class Custom404Middleware(object): 
    def process_exception(self, request, exception): 
     if isinstance(exception, Http404): 
      # implement your custom logic. You can send 
      # http response with any template or message 
      # here. unicode(exception) will give the custom 
      # error message that was passed. 
      msg = unicode(exception) 
      return HttpResponse(msg, status=404) 

中間件設置

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware', 
    'django.contrib.sessions.middleware.SessionMiddleware', 
    'django.middleware.csrf.CsrfViewMiddleware', 
    'django.contrib.auth.middleware.AuthenticationMiddleware', 
    'django.contrib.messages.middleware.MessageMiddleware', 
    'college.middleware.Custom404Middleware', 
    # Uncomment the next line for simple clickjacking protection: 
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware', 
) 

這將這樣的伎倆。如果我做錯了任何事情,請糾正我。希望這可以幫助。

2

在視圖內部增加一個Http404異常。通常在您遇到DoesNotExist異常時完成。例如:

from django.http import Http404 

def article_view(request, slug): 
    try: 
     entry = Article.objects.get(slug=slug) 
    except Article.DoesNotExist: 
     raise Http404() 
    return render(request, 'news/article.html', {'article': entry, }) 

更妙的是,使用get_object_or_404 shortcut

from django.shortcuts import get_object_or_404 

def article_view(request): 
    article = get_object_or_404(MyModel, pk=1) 
    return render(request, 'news/article.html', {'article': entry, }) 

如果您想自定義默認404 Page not found響應,把你稱爲404.html自己的模板到templates文件夾。