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‘),
]
project.html
文件<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AutoPlarform Home</title>
</head>
<body>
{{ project }}
</body>
</html>
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‘)
原文:https://www.cnblogs.com/yiluotalk/p/13580007.html