Python圈Python基础

Django基础6--抛出404异常

2020-08-28  本文已影响0人  伊洛的小屋
1.抛出404错误
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')

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'),
]

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>AutoPlarform Home</title>
</head>
<body>
{{ project }}
</body>
</html>
2.快捷函数: get_object_or_404()

Django还提供了一个快捷的函数来实现上面的功能

# 作者:伊洛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')

欢迎下方【戳一下】【点赞】
Author:伊洛Yiluo
愿你享受每一天,Just Enjoy !

上一篇 下一篇

猜你喜欢

热点阅读