Sunday, November 10, 2019

Custom 404 Page for Django CMS

For a side project, I needed a 404 page that was editable by users in Django CMS. Suffice it say, it took a while to figure out how to do it without having the Django cache the CMS page response and provide the right 404 http status code. Other techniques wrongly serve the page as a 200 OK which is wrong for search engines.
  1. First create a 404 page in Django CMS and publish it.
  2. Set you handler404 in your (change the path to your view file accordingly):
    handler404 = 'shared.views.page_not_found'
  3. The view:

    1:  from cms.views import details  
    2:  from django.http import HttpResponse  
    3:  def page_not_found(request, exception):  
    4:    response = details(request, '404')  # 404 is the slug you named your page in Django CMS
    5:    return HttpResponse(content=response.rendered_content, content_type='text/html; charset=utf-8', status=404)  

No comments:

Post a Comment