I’ve tried importing and editing handler404
in urls.py
, made sure pointed to right template etc but kept getting server 500 error responses. The only way I could get it to work was changing return render(
to return HttpResponseNotFound(
but in that case I only get the text representation of ‘mysite.views.404_error.html’ as need to return HTML directly with HttpResponseNotFound
. Wondering what is the correct way to return a custom 404 error template. Thanks a lot.
Asked
Active
Viewed 565 times
2

daytony
- 398
- 3
- 9
-
1https://docs.djangoproject.com/en/3.2/topics/http/views/#the-http404-exception – michjnich Jun 15 '21 at 10:32
2 Answers
3
We can render the template with render_to_string(…)
and then wrap the result in a HttpResponseNotFound
:
from django.http import HttpResponseNotFound
from django.template.loader import render_to_string
def my_404_handler(request, exception, template_name='404.html'):
context = {} # some context
content = render_to_string(
'some-template-name.html',
context,
request
)
return HttpResponseNotFound(content)
We here thus render a template some-template-name.html
, and the content
; the result of the function, is then returned with a HttpResponseNotFound
.

Willem Van Onsem
- 443,496
- 30
- 428
- 555
-
2This looks exactly what I need will try when back at laptop. Thanks a million. Is 404.html a set name that must be used? – daytony Jun 15 '21 at 10:47
0
For me the only solution that worked (Django 3.7) dev/prod is here
Please see @elano7 answer

Abpostman1
- 158
- 1
- 8