2

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.

daytony
  • 398
  • 3
  • 9

2 Answers2

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
  • 2
    This 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