Django404 handler did not raise Http404 ()

When I override handler404 and handler500 in my urls.py for example:

from myapp.views import not_found_view

handler404 = not_found_view
handler500 = not_found_view

      

and call raise Http404()

in my middleware, I see my 404 page.

When I remove both from handler404

and handler500

from mine urls.py

and raise Http404()

in my middleware, I see a default error page of 500 (from Django Suit) - hence the reason I am trying to set a custom 404 template to be used in raise Http404()

.

Now my problem is, when I uninstall handler500 and install only handler404 , I also see the HTTP 500 page !: |

Why is mine being handler500

called when I raise Http404()

??

I have multiple template directories in multiple applications, I tried to place 404.html

in my main application which contains settings and in another "regular" application, but it didn't work.

I installed DEBUG

in False

.

Hope someone can answer my question!

+3


source to share


3 answers


You don't need to write your own handlers if you just want to replace the Django template. Django uses 404.html

and 500.html

files for patterns, and you can replace them in a file with the same name in the directory specified settings.TEMPLATE_DIRS

.

In your example, this means that you can create files myapp/templates/404.html

and myapp/templates/500.html

.



Note that you need to set DEBUG

in False

to select these templates.

Check this article for more details.

+6


source


Another solution is to replace (monkey-patch) Django page_not_found.

from django.views import defaults
from myapp.views import not_found_view

defaults.page_not_found = not_found_view

      



Monkey-patching is bad practice and may stop working if Django updates the internal API, but it can still be useful in some situations. Ex. if for some reason other methods don't work.

0


source


I faced a similar situation. My custom 404 handler WAS called, but my browser response showed a 500 error.

After checking, I encountered a syntax error in the template. So 500 were caused by this. I fixed the template and the result was as desired.

The catch 22 is that the default template is debug == debug, so if you set DEBUG = False, then debugging the template will also be false; You will see a 500 error with no template error tracing.

So put a print () statement in the handler404 view just before render () returns. If you see the output in your django console, you will know that the error is in your template.

You can also try this in your settings.py file (django 1.8+), but it didn't seem to work for me and I didn't follow through once I fixed the template.

TEMPLATES = [
    {

        'OPTIONS': {
             'debug': True,
         }
    },

      

0


source







All Articles