Django custom 404 page not working

Viewed 13597

So, in my projects I wanted to add a custom 404 error page, so I followed what I could find on the web, but nothing seemed to work for me.

This is what I have on my files:

settings.py

import os
# Django settings for HogwartsMail project.

PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))

DEBUG = False
TEMPLATE_DEBUG = DEBUG

# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = ["*"]

urls.py

urlpatterns = patterns('',
    ...
)

handler404 = "HogwartsMail.views.error404"

views.py

def error404(request):
    return render(request,'404.html')

Whenever I try to enter a random url, though, instead of getting a 404 error, I get a Server Error (500).

As I've said, i tried it many different ways, but none actually worked for me.

Also, another problem I am having is that the pages I have load really slowly and they don't open the styling or images, so I assume that, when DEBUG = False, I need everything to be already online. Is that correct?

5 Answers

As a best practice I've add 2 urls.py in my project. So I add handler404 in my base urls.py. my parent urls.py is look like this

from django.conf.urls import handler404
import myapp

urlpatterns = [
   path('', include('myapp.urls')),
   path('admin/', admin.site.urls),
]

handler404 = myapp.views.error_404

and error_404 is a view in my views.py. like this

def error_404(request, exception):
    data = {"name": "somthing error"}
    return render(request,'myapp/404.html', data)

check the full tutorial here

Related