2013-05-03 62 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文件夹。