我们已经实现了一个展示标题列表的页面,现在看看如何实现点击标题查看文章详情内容:
修改文章列表页的li,增加超链接:
<li><a href="{{ blog.id }}">{{ blog.title }}a>li>
点击某一个超链接:我们发现浏览器跳转的URL变成了http://127.0.0.1:8000/blog/5
;
获取id为5的article:
from blog.models import BlogArticles
article = BlogArticles.objects.get(id=1)
知道了如何获取指定id的article对象,现在先编辑blog/views.py
,增加响应查看文章详情的请求函数blog_article
:
def blog_article(request, article_id):
article = BlogArticles.objects.get(id=article_id)
pub = article.publish
return render(request, "blog/content.html", {"article": article, "publish": pub})
创建与之对应的模板:blog/template/blog/content.html
{% extends "base.html" %}
{% block title %}
blog article
{% endblock %}
{% block content %}
<div class="row text-center vertical-middle-sm">
<h1>{{article.title}}h1>
div>
<div class="row">
<div class="col-xs-12 col-md-8">
<p class="text-center">
<span>{{article.author.username}}span>
<span style="margin-left: 20px;">{{publish}}span>
<div>{{article.body}}div>
p>
div>
<div class="col-xs-6 col-md-4">
<h2>广告h2>
<p>读书笔记p>
<img width="200px"
src="https://i0.hdslb.com/bfs/face/a0d8a470a7b7b1175c9cc43a88ee4adcd9a97851.jpg@68w_68h.webp">
div>
div>
{% endblock %}
blog/urls.py
文件中增加新的URL路径;from django.conf.urls import url
from . import views
urlpatterns = [
# r"^$" :表示访问当前应用的根目录,对应:http://127.0.0.1:8000/blog/
# views.blog_title :声明了响应这个请求的函数对象
url(r"^$", views.blog_title, name="blog_title"),
url(
r"(?P\d)/$" , views.blog_article, name="blog_detail"
), # 可以取到列表超链接赋的id值
]
如果修改访问url为http://127.0.0.1:8000/blog/6
,浏览器会显示十分详尽的错误信息:
DoesNotExist at /blog/6/
BlogArticles matching query does not exist.
...
这是因为目前在Debug模式下,错误信息会尽可能的详尽,便于调试;
blog/views.py
中的blog_article()
函数;from django.shortcuts import render, get_object_or_404
# Create your views here.
from .models import BlogArticles
def blog_title(request):
blogs = BlogArticles.objects.all()
return render(request, "blog/titles.html", {"blogs": blogs})
def blog_article(request, article_id):
# article = BlogArticles.objects.get(id=article_id)
article = get_object_or_404(BlogArticles, id=article_id)
pub = article.publish
return render(request, "blog/content.html", {"article": article, "publish": pub})
再访问id=6的url页面,会显示404页面:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/blog/6/
Raised by: blog.views.blog_article
get_object_or_404()
方法raise Http404()
来处理;get_object_or_404(kclass, *args, **kwargs)
类似的Django中海油很对的默认方法,可以帮助提高开发效率,减少代码量;
至此,我们完成了一个网站开发的最基础结构:博客应用。