Customized 404.html does not reflect

Asked 2 years ago, Updated 2 years ago, 79 views

Thank you for your help.Let me ask you the following questions.
The django version is 3.1.7.

What do you want to achieve

I want the customized 404.html to be displayed when I get 404 errors.

What we've done so far

  • views.py returns 404 errors with get_object_or_404.
  • Created new templates in the root directory.Create 404.html in it.
  • Add importos to settings.py (because "os is not defined.")
  • Add os.path.join(BASE_DIR, 'templates') to settings.py-TEMPLATES-'DIRS'

Results of the above

Only the default 404 error page appears.
The 404 customized pages do not appear.

python python3 django

2022-09-30 18:16

1 Answers

On django 3.1.7 in Windows 10, I ran the trailing powershell script to verify it worked, and the custom 404 was displayed correctly.
Please check the settings below for errors.

  • Creating a templates folder in the same hierarchy as
  • manage.py
  • Toggling settings.py to DEBUG=False
    (Debug mode forces detailed error messages to appear )

手順I omitted the procedure because it would be redundant, but I confirmed that custom 404 will be displayed if you call get_object_or_404 by creating polls.py.

powershell script:

Create a new project page in #C:\django
$django="C:\django" 
if (-not(Test-Path$django)) {mkdir$django}
cd$django
#rm-rmysite
django-admin startproject mysite

# template creation
cd$django\mysite\
mkdir templates
"Hello 404." | Out-File".\templates\404.html" - Encoding default

# Replace settings.py
cd.\mysite\
$settings=Get-Content settings.py
$settings=$settings-replace "'DIRS':\[\], ", "DIRS': [os.path.join(BASE_DIR, 'templates')], " 
$settings=$settings-replace "import Path", "import Path`r`nimportos" 
# Debug mode does not read 404.html, so change to production mode
$settings=$settings-replace "DEBUG=True", "DEBUG=False" 
$settings=$settings-replace "ALLOWED_HOSTS=\[\]", "ALLOWED_HOSTS=['127.0.0.1']" 
# overwrite preservation
$settings | Out-File ".\settings.py" - Encoding default

# execution
cd$django\mysite\
start "python" - ArgumentList "manage.py", "runserver" - PassThru
start "http://127.0.0.1:8000/polls/" 


2022-09-30 18:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.