我的Django应用程序有一个小问题:我的项目是一个博客,上面有几篇文章。您可以通过在网址栏中输入localhost:8000/blog/post/1
来访问第一篇文章。阅读帖子编号。 X,您必须输入localhost:8000/blog/post/X
。因此,当请求的帖子不存在时,我需要显示一个自定义的“错误404”页面(例如,如果只有3个帖子可用,例如localhost:8000/blog/post/32
)。问题是,它引发了 Server Error(500)错误,而不是引发404错误,但是我从来没有编写任何代码来引发此类错误。
这是有关的代码部分,但不是我认为没有用的完整代码。
项目名称为red_pillers
,应用程序名称为blog
。
在red_pillers / settings.py
中DEBUG = False
ALLOWED_HOSTS = ['127.0.0.1', 'localhost']
red_pillers / 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_pillers / 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)
博客/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})