018-Django 404 Page Not Found

Objectives: Django 404 Page Not Found

Django 404 Page Not Found

Django 404 (Page Not Found)

1. What Happens on a 404 Error?

If you request a URL that does not exist, Django shows a 404 error. Try this in your browser:

127.0.0.1:8000/masfdfg/

You will see one of two results:

  1. The default Django 404 page.
  2. The Django debug page if DEBUG = True.

Tip:

To see the real 404 page, set DEBUG = False in settings.py and specify allowed hosts.

2. Set DEBUG = False and Allowed Hosts

Open settings.py and edit these lines:

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*']  # Use your domain name in production

Now, visiting 127.0.0.1:8000/masfdfg/ will show the built-in 404 page.

3. Customize the 404 Template

Django looks for 404.html in your templates folder. If it exists, Django will use it for 404 errors.

Create 404.html in members/templates/:



Wrong address

Ooops!


I cannot find the file you requested!



Now, visiting 127.0.0.1:8000/masfdfg/ will show your custom 404 page.

4. Reset DEBUG to True

After testing, reset DEBUG = True in settings.py to continue development:

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []

Example Summary:

  • Accessing a non-existing page triggers a 404 error.
  • Customize the message by creating 404.html in your templates folder.
  • Always reset DEBUG = True during development to see debug messages.

5. Exercises (10 Q&A)

  1. Q: What happens when you visit a non-existent URL with DEBUG = True?
    A: Django shows the debug page with detailed error information.
  2. Q: What happens when DEBUG = False?
    A: Django shows the 404 template page or a default "Not Found" message.
  3. Q: Where should you put the custom 404 page?
    A: In the templates folder, named 404.html.
  4. Q: How do you make Django allow your local host when DEBUG = False?
    A: Set ALLOWED_HOSTS = ['*'] for development.
  5. Q: What HTML elements can you use in 404.html?
    A: Any HTML elements to display a friendly message.
  6. Q: Can you customize 404.html differently for production?
    A: Yes, you can include images, styling, and helpful navigation links.
  7. Q: Why should you reset DEBUG = True after testing?
    A: To continue seeing detailed debug errors during development.
  8. Q: Does Django automatically create 404.html?
    A: No, Django provides a default template if 404.html does not exist.
  9. Q: Can you link back to the main page from 404.html?
    A: Yes, you can add a hyperlink to improve user navigation.
  10. Q: How can you test your 404 page locally?
    A: Visit a random URL that doesn’t exist, like 127.0.0.1:8000/randompage/.

Reference Book: N/A

Author name: SIR H.A.Mwala Work email: biasharaboraofficials@gmail.com
#MWALA_LEARN Powered by MwalaJS #https://mwalajs.biasharabora.com
#https://educenter.biasharabora.com

:: 1::