簡體   English   中英

如何制作自定義錯誤頁面 django 2.2

[英]How to make custom error pages django 2.2

我正在使用 Django 2.2 創建一個博客,我最近幾乎完成了所有這些。 剩下的就是制作自定義錯誤頁面。 我有一本書展示了如何做到這一點,但它不起作用。 我已經在網上查遍了,但沒有任何效果。 請幫忙? 這是代碼:

設置.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

視圖.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)

網址.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

這是我收到的錯誤消息:

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

正如錯誤所指定的,視圖需要采用兩個參數, requestexception

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)
    )

你應該讓它返回一個HttpResponseNotFound object [Django-doc] ,所以我們可以在這里調用render_to_string來首先將模板渲染成一個字符串,然后將它包裝在一個HttpResponseNotFound中。

該異常包含異常 object。 例如,您可以從此 object 中閱讀詳細信息並將其添加到異常頁面。

handler404的文檔中指定:

(...) 如果您實現自定義視圖,請確保它接受requestexception arguments 並返回HttpResponseNotFound

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM