1. 程式人生 > 實用技巧 >Django基礎6--丟擲404異常

Django基礎6--丟擲404異常

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
  • 這樣就簡化了一開始的過程,看上去更加的簡潔,而且會降低模型層和檢視層的耦合性