Error handler not rendering template properly

So, I have error 404 handler in my project. When it is called, django doesn’t render the template properly.
Template

<script>
    authorize("{{ address }}")
</script>

Urls

handler404 = views.error_404

Views

def error_404(request, exception):
    return render(request, '404.html', context={"address": "http://192.168.1.150:8000/"})

So, I would expect it to be rendered like this:

<script>
    authorize("http://192.168.1.150:8000/")
</script>

But instead, it looks like this:

<script>
    authorize("")
</script>

When I render this template via normal view instead of error handler - it works properly. Does anyone know why this happens or how can I fix this?
Thanks!

Did you check error_404 is really called by breaking it in some way, e.g. assert 0 ? What you’re seeing implies {{ address }} can’t be found in the context so it looks like the view function isn’t being used!

Maybe it’s the line in your project/urls.py.

Instead of:
handler404 = views.error_404

It should be
handler404 = 'your_app.views.error_404'

More information can be found in the docs

I could be wrong but, wouldn’t assert 0 call the error 500 handler?

Turns out, error_404 actually wasn’t called, instead django was rendering my 404.html by itself. Nitinpaul’s advice helped fix it - before it was

handler404 = views.error_404

in my “my_app/urls.py”, after I changed it to

handler404 = 'my_app.views.error_404'

and put it in my “project/urls.py” it started working properly. Thanks a lot!

2 Likes