简体   繁体   中英

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. 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:

    """
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:

    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:

    """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 :

from django.http import HttpResponseNotFound
from django.template.loader import render_to_string

def custom_404(request):
    return HttpResponseNotFound(
        '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 .

The exception contains the exception object. You can for example read details from this object and add these to the exception page.

This is specified in the documentation on handler404 :

(…) If you implement a custom view, be sure it accepts request and exception arguments and returns an HttpResponseNotFound .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM