[英]How to make custom error pages django 2.2
I am creating a blog using Django 2.2, and I have recently finished almost all of it.我正在使用 Django 2.2 创建一个博客,我最近几乎完成了所有这些。 All that is left is making custom error pages.
剩下的就是制作自定义错误页面。 I have a book that shows how to do it, but it doesn't work.
我有一本书展示了如何做到这一点,但它不起作用。 I have checked all over online, but nothing works.
我已经在网上查遍了,但没有任何效果。 Please help?
请帮忙? Here is the code:
这是代码:
settings.py:设置.py:
"""
Django settings for boy_talks_about_coding project.
Generated by 'django-admin startproject' using Django 2.2.12.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '8rk31cd@y065q)l9z2x@4j#a*gz6g3lw_$$g3e7#@de4xyj#xg'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['localhost''boytalksaboutcoding.com''boytalksaboutcoding.herokuapp.com']
# Application definition
INSTALLED_APPS = [
# My apps
'blog_posts',
# Third party apps
'bootstrap4',
# Default Django apps
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'boy_talks_about_coding.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'boy_talks_about_coding.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'blog_posts/static'),
)
# Heroku settings
import django_heroku
django_heroku.settings(locals())
if os.environ.get('DEBUG') == 'TRUE':
DEBUG = True
elif os.environ.get('DEBUG') == 'FALSE':
DEBUG = False
views.py:视图.py:
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
"""The home page for my blog."""
return render(request, 'blog_posts/index.html')
def old_posts(request):
"""Where I will show earlier posts."""
return render(request, 'blog_posts/old_posts.html')
def todays_post(request):
"""Where I will show this week's post."""
return render(request, 'blog_posts/todays_post.html')
def custom_404(request):
return render(request, 'blog_posts/404.html', status=404)
def custom_500(request):
return render(request, 'blog_posts/500.html', status=500)
urls.py:网址.py:
"""Defines URL patterns for blog_posts."""
from django.urls import path
from django.conf.urls.static import static
from django.conf import settings
from django.http import HttpResponse
from django.conf.urls import *
from . import views
app_name = 'blog_posts'
urlpatterns = [
# Home page
path('', views.index, name='index'),
# This week's post
path('this-weeks-post/', views.todays_post, name="todays_post"),
# Earlier posts
path('earlier-posts/', views.old_posts, name="old_posts"),
] + static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
handler404 = views.custom_404
handler500 = views.custom_500
Here is the error message I get:这是我收到的错误消息:
Performing system checks...
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/Users/isaac/opt/anaconda3/lib/python3.7/threading.py", line 926, in _bootstrap_inner
self.run()
File "/Users/isaac/opt/anaconda3/lib/python3.7/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "/Users/isaac/Desktop/blog/b_env/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "/Users/isaac/Desktop/blog/b_env/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
self.check(display_num_errors=True)
File "/Users/isaac/Desktop/blog/b_env/lib/python3.7/site-packages/django/core/management/base.py", line 436, in check
raise SystemCheckError(msg)
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:
ERRORS:
?: (urls.E007) The custom handler404 view 'blog_posts.views.custom_404' does not take the correct number of arguments (request, exception).
System check identified 1 issue (0 silenced).
As specified by the error, the view needs to take two parameters, the request
, and the exception
:正如错误所指定的,视图需要采用两个参数,
request
和exception
:
from django.http import HttpResponseNotFound
from django.template.loader import render_to_string
def custom_404(request
, exception):
return HttpResponseNotFound(
render_to_string('blog_posts/404.html', request=request
)
)
You should let it return a HttpResponseNotFound
object [Django-doc] , so we can here call render_to_string
to first render the template to a string, and then wrap it in a HttpResponseNotFound
.你应该让它返回一个
HttpResponseNotFound
object [Django-doc] ,所以我们可以在这里调用render_to_string
来首先将模板渲染成一个字符串,然后将它包装在一个HttpResponseNotFound
中。
The exception contains the exception object.该异常包含异常 object。 You can for example read details from this object and add these to the exception page.
例如,您可以从此 object 中阅读详细信息并将其添加到异常页面。
This is specified in the documentation on handler404
:这在
handler404
的文档中指定:
(…) If you implement a custom view, be sure it accepts
request
andexception
arguments and returns anHttpResponseNotFound
.(...) 如果您实现自定义视图,请确保它接受
request
和exception
arguments 并返回HttpResponseNotFound
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.