【发布时间】:2019-08-20 10:12:12
【问题描述】:
我的 Django 应用程序有一个小问题:我的项目是一个包含几篇文章的博客。您可以通过在 URL 栏中输入 localhost:8000/blog/post/1 来访问第一篇文章。阅读帖子号。 X 你必须输入localhost:8000/blog/post/X。因此,当请求不存在的帖子时,我需要显示一个自定义的“错误 404”页面(例如 localhost:8000/blog/post/32,如果只有 3 个帖子可用)。问题是,它不是抛出 404 错误,而是抛出 Server Error (500) 错误,但是我从未编写过代码来抛出这种错误。
这是相关的代码部分,但不是我认为没用的完整代码。
项目名称为red_pillers,应用名称为blog。
在 red_pilers/settings.py 中
DEBUG = False
ALLOWED_HOSTS = ['127.0.0.1', 'localhost']
red_pilers/urls.py
from django.contrib import admin
from django.urls import path, re_path, include
from django.conf.urls import handler404
from . import views
handler404 = 'red_pillers.views.handler404'
urlpatterns = [
re_path('^blog/', include('blog.urls')),
re_path('^$', views.home),
re_path('^admin/', admin.site.urls),
]
red_pilers/views.py
from django.shortcuts import render
def home(request):
return render(request, 'home.html')
def handler404(request):
return render(request, 'errors/404.html', {}, status=404)
blog/pycode/post.py
from django.http import Http404
class Post:
POSTS = [
{'id': 1, 'title': 'First Post', 'body': 'This is my first post'},
{'id': 2, 'title': 'Second Post', 'body': 'This is my second post'},
{'id': 3, 'title': 'Third Post', 'body': 'This is my third post'},
]
@classmethod
def all(cls):
return cls.POSTS
@classmethod
def find(cls, id):
try:
return cls.POSTS[int(id) - 1]
except:
raise Http404('Error 404...')
编辑:添加更多代码
blog/urls.py
from django.urls import path, re_path
from . import views
urlpatterns = [
re_path('^$', views.index),
re_path('^posts/(?P<id>[0-9]+)$', views.show),
]
blog/views.py
from django.shortcuts import render
from .pycode.post import Post
def index(request):
posts = Post.all()
return render(request, 'blog/index.html', {'posts': posts})
def show(request, id):
post = Post.find(id)
return render(request, 'blog/show.html', {'post': post})
【问题讨论】:
-
如果您遇到 500 错误,请向我们展示完整的错误跟踪。如果您的代码遇到 python 错误,则会收到 500 错误。请注意,您的
home视图除了渲染 home.html(它不使用Post)之外什么都不做,所以除非 home.html 中有一个奇怪的模板标签,否则它不会引发错误。您没有向我们展示任何相关代码,因为您在此处向我们展示的任何代码都与获取 url /blog/post/32 无关。 -
我添加了更多代码,你可以看看吗?
-
我怎样才能显示完整的错误跟踪?终端里什么都没有……
-
你在哪里
manage.py runserver你应该看到详细的错误日志。 -
就
[30/Mar/2019 15:55:45] "GET /blog/posts/4 HTTP/1.1" 500 27
标签: django http-status-code-404