1.抛出404错误
- 当内容不存在时,需要返回404
- 回到
views.py
,改写project_list
from django.http import HttpResponse, Http404
from django.shortcuts import render
from .models import ProjectInfo
# Create your views here.
def home(request):
project_list = ProjectInfo.objects.order_by('add_data')[:5]
context = {'project_list': project_list}
return render(request, 'autoapi/home.html', context)
def project_list(request, project_id):
try:
project = ProjectInfo.objects.get(pk=project_id)
context = {'project': project}
except ProjectInfo.DoesNotExist:
raise Http404('project list dose not exist')
return render(request, 'autoapi/project.html', context)
def register(request):
return HttpResponse('You\'re looking at the register page')
- 回到
url.py
改写一下,project_list
from django.urls import path
from . import views
urlpatterns = [
path('home/', views.home, name='index'),
path('<int:project_id>/', views.project_list, name='project list'),
path('register/', views.register, name='register'),
]
- 在/AutoPlatform/autoapi/templates下新建一个
project.html
文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AutoPlarform Home</title>
</head>
<body>
{{ project }}
</body>
</html>
-
来先看下全面的列表
- 数据中只有4个列表,那么如果输入id 为5的话,按照上面的代码逻辑应该就会抛出404异常的错误了
-
来先看看id = 1
-
再看看id = 4
-
边界值都看过了,那么现在我们来输入一个不存在数据的id,测试一下是否会抛出404的异常
- 抛出了project list dose not exist的异常
2.快捷函数: get_object_or_404()
Django还提供了一个快捷的函数来实现上面的功能
- 现在来再改写一个views.py
# 作者:伊洛Yiluo 公众号:伊洛的小屋
# 个人主页:https://yiluotalk.com/
# 博客园:https://www.cnblogs.com/yiluotalk/
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render
from .models import ProjectInfo
# Create your views here.
def home(request):
project_list = ProjectInfo.objects.order_by('add_data')[:5]
context = {'project_list': project_list}
return render(request, 'autoapi/home.html', context)
def project_list(request, project_id):
project = get_object_or_404(ProjectInfo, pk=project_id)
context = {'project': project}
return render(request, 'autoapi/project.html', context)
def register(request):
return HttpResponse('You\'re looking at the register page')
-
打开一个存在的id
-
打开一个不存在的id
- 这样就简化了一开始的过程,看上去更加的简洁,而且会降低模型层和视图层的耦合性
欢迎下方【戳一下】【点赞】
Author:伊洛Yiluo
愿你享受每一天,Just Enjoy !
网友评论