Django raising 404 with a message

后端 未结 9 1186
有刺的猬
有刺的猬 2020-12-19 05:31

I like to raise 404 with some error message at different places in the script eg: Http404(\"some error msg: %s\" %msg) So, in my urls.py I included:

<         


        
9条回答
  •  半阙折子戏
    2020-12-19 06:32

    Generally there should not be any custom messages in 404 errors bu if you want to implement it you can do this using django middlewares.

    Middleware

    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)
    

    Middlewares Settings

    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',
    )
    

    This will do the trick. Correct me if I am doing any thing wrong. Hope this helps.

提交回复
热议问题