配置tamplates文件路径、关闭Debug、配置allowrd_hosts
from django.shortcuts import render
def page_not_found(request):
return render(request, '404.html')
def page_error(request):
return render(request, '500.html')
def permission_denied(request):
return render(request, '403.html')
...
from myapp.views import *
handler403 = permission_denied
handler404 = page_not_found
handler500 = page_error
...
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 917, in _bootstrap_inner
self.run()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 865, in run
self._target(*self._args, **self._kwargs)
File "/Users/darkmoon/PycharmProjects/LDjango1/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "/Users/darkmoon/PycharmProjects/LDjango1/venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
self.check(display_num_errors=True)
File "/Users/darkmoon/PycharmProjects/LDjango1/venv/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 handler400 view 'mysite.views.bad_request' does not take the correct number of arguments (request, exception).
?: (urls.E007) The custom handler403 view 'mysite.views.permission_denied' does not take the correct number of arguments (request, exception).
?: (urls.E007) The custom handler404 view 'mysite.views.page_not_found' does not take the correct number of arguments (request, exception).
System check identified 3 issues (0 silenced).
仔细研究发现,视图函数缺少了参数,咋们先看看默认错误视图的源代码:
from urllib.parse import quote
from django.http import (
HttpResponseBadRequest, HttpResponseForbidden, HttpResponseNotFound,
HttpResponseServerError,
)
from django.template import Context, Engine, TemplateDoesNotExist, loader
from django.views.decorators.csrf import requires_csrf_token
ERROR_404_TEMPLATE_NAME = '404.html'
ERROR_403_TEMPLATE_NAME = '403.html'
ERROR_400_TEMPLATE_NAME = '400.html'
ERROR_500_TEMPLATE_NAME = '500.html'
# This can be called when CsrfViewMiddleware.process_view has not run,
# therefore need @requires_csrf_token in case the template needs
# {% csrf_token %}.
@requires_csrf_token
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME):
"""
Default 404 handler.
Templates: :template:`404.html`
Context:
request_path
The path of the requested URL (e.g., '/app/pages/bad_page/'). It's
quoted to prevent a content injection attack.
exception
The message from the exception which triggered the 404 (if one was
supplied), or the exception class name
"""
exception_repr = exception.__class__.__name__
# Try to get an "interesting" exception message, if any (and not the ugly
# Resolver404 dictionary)
try:
message = exception.args[0]
except (AttributeError, IndexError):
pass
else:
if isinstance(message, str):
exception_repr = message
context = {
'request_path': quote(request.path),
'exception': exception_repr,
}
try:
template = loader.get_template(template_name)
body = template.render(context, request)
content_type = None # Django will use DEFAULT_CONTENT_TYPE
except TemplateDoesNotExist:
if template_name != ERROR_404_TEMPLATE_NAME:
# Reraise if it's a missing custom template.
raise
# Render template (even though there are no substitutions) to allow
# inspecting the context in tests.
template = Engine().from_string(
'Not Found
'
'The requested resource was not found on this server.
')
body = template.render(Context(context))
content_type = 'text/html'
return HttpResponseNotFound(body, content_type=content_type)
@requires_csrf_token
def server_error(request, template_name=ERROR_500_TEMPLATE_NAME):
"""
500 error handler.
Templates: :template:`500.html`
Context: None
"""
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist:
if template_name != ERROR_500_TEMPLATE_NAME:
# Reraise if it's a missing custom template.
raise
return HttpResponseServerError('Server Error (500)
', content_type='text/html')
return HttpResponseServerError(template.render())
@requires_csrf_token
def bad_request(request, exception, template_name=ERROR_400_TEMPLATE_NAME):
"""
400 error handler.
Templates: :template:`400.html`
Context: None
"""
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist:
if template_name != ERROR_400_TEMPLATE_NAME:
# Reraise if it's a missing custom template.
raise
return HttpResponseBadRequest('Bad Request (400)
', content_type='text/html')
# No exception content is passed to the template, to not disclose any sensitive information.
return HttpResponseBadRequest(template.render())
# This can be called when CsrfViewMiddleware.process_view has not run,
# therefore need @requires_csrf_token in case the template needs
# {% csrf_token %}.
@requires_csrf_token
def permission_denied(request, exception, template_name=ERROR_403_TEMPLATE_NAME):
"""
Permission denied (403) handler.
Templates: :template:`403.html`
Context: None
If the template does not exist, an Http403 response containing the text
"403 Forbidden" (as per RFC 7231) will be returned.
"""
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist:
if template_name != ERROR_403_TEMPLATE_NAME:
# Reraise if it's a missing custom template.
raise
return HttpResponseForbidden('403 Forbidden
', content_type='text/html')
return HttpResponseForbidden(
template.render(request=request, context={'exception': str(exception)})
)
我们发现,咋们自定义的视图缺少了exception,我们自己给补上就可以正常运行了。
def bad_request(request, exception, template_name='400.html'):
return render(request, template_name)
def permission_denied(request, exception, template_name='403.html'):
return render(request, template_name)
def page_not_found(request, exception, template_name='404.html'):
return render(request, template_name)
def server_error(request, template_name='500.html'):
return render(request, template_name)
此时可以正常运行了!!!