首页 > 其他 > 详细

Django基础6--抛出404异常

时间:2020-08-28 23:25:46      阅读:81      评论:0      收藏:0      [点我收藏+]
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
    技术分享图片
  • 这样就简化了一开始的过程,看上去更加的简洁,而且会降低模型层和视图层的耦合性

Django基础6--抛出404异常

原文:https://www.cnblogs.com/yiluotalk/p/13580007.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!