有了文章列表页面后,固然还须要详情页面,方便用户对某一篇感兴趣的文章深刻阅读。html
打开article/views.py
,增长文章详情页面的视图函数article_detail()
:python
article/views.py ... # 文章详情 def article_detail(request, id): # 取出相应的文章 article = ArticlePost.objects.get(id=id) # 须要传递给模板的对象 context = { 'article': article } # 载入模板,并返回context对象 return render(request, 'article/detail.html', context)
article_detail(request, id)
函数中多了id
这个参数。注意咱们在写model的时候并无写叫作id的字段,这是Django自动生成的用于索引数据表的主键(Primary Key,即pk)。有了它才有办法知道到底应该取出哪篇文章。ArticlePost.objects.get(id=id)
意思是在全部文章中,取出id值相符合的惟一的一篇文章。而后编写article/urls.py
,配置路由地址:git
article/urls.py ... urlpatterns = [ ... # 文章详情 path('article-detail/<int:id>/', views.article_detail, name='article_detail'), ]
<int:id>
:Django2.0的path
新语法用尖括号<>定义须要传递的参数。这里须要传递名叫id
的整数到视图函数中去。github
重申一下老版本的Django是没有path
语法的。django
在templates/article/
中新建detail.html
文件,编写以下代码:浏览器
templates/article/detail.html <!-- extends代表此页面继承自 base.html 文件 --> {% extends "base.html" %} {% load staticfiles %} <!-- 写入 base.html 中定义的 title --> {% block title %} 文章详情 {% endblock title %} <!-- 写入 base.html 中定义的 content --> {% block content %} <!-- 文章详情 --> <div class="container"> <div class="row"> <!-- 标题及做者 --> <h1 class="col-12 mt-4 mb-4">{{ article.title }}</h1> <div class="col-12 alert alert-success">做者:{{ article.author }}</div> <!-- 文章正文 --> <div class="col-12"> <p>{{ article.body }}</p> </div> </div> </div> {% endblock content %}
这里咱们用{{ article.xxx }}
取出了文章标题、做者以及正文。服务器
前面咱们已经经过后台建立了几篇文章,这里将取出id为1的一篇文章测试效果。app
运行开发服务器后,在浏览器中输入http://127.0.0.1:8000/article/article-detail/1/
:函数
虽然已经实现了文章详情功能,可是经过输入url访问的方式实在太不友好。学习
改写header.html
,让用户可经过导航栏右侧的文章连接返回首页:
templates/header.html ... <div> <ul class="navbar-nav"> <li class="nav-item"> <!-- 改写了这里的 href --> <a class="nav-link" href="{% url 'article:article_list' %}">文章</a> </li> </ul> </div> ...
注意看这里href是如何改写的:
{% url '...' %}
是Django规定的语法,用于指明具体地址关于其中的'article:article_list'
的解释:
article
是在项目根目录的urls.py
中定义的app的名称article_list
是在app中的urls.py
中定义的具体的路由地址经过这样的方法就将连接跳转的指向给配置好了,只要对应url的名称不变,url自己不管怎么变化,Django均可以解析到正确的地址,很灵活。
固然你也能够直接在href
中写入url的地址,可是一旦url有变化,全部相关的连接都会失效,下降维护性。
而后再改写list.html
,让用户可点击阅读本文按钮进入文章详情:
templates/article/list.html ... <div class="card-footer"> <!-- 一样改写 href --> <a href="{% url 'article:article_detail' article.id %}" class="btn btn-primary">阅读本文</a> </div> ...
留意文章的id是如何传递的:
list.html
中,经过href="{% url 'article:article_detail' article.id %}"
,将id传递给article/urls.py
article/urls.py
中,经过<int:id>
传递给视图函数article_detail()
article_detail()
中,经过形参id
取得了文章的id值,并进行处理,最终定位了须要获取的文章对象如今咱们能够经过连接访问网站上的不一样页面了,而不须要手动输入url。固然这也是现代网站的基础。
如今咱们也拥有查看文章详情的功能了,而且优化了网页切换的体验。
下一章将学习使用Markdown语法对文章正文进行排版。
转载请告知做者并注明出处。