Django 搭建简易博客之三 - 使用动态URL

动态 URL 技术

运行已经做好的博客,会发现只有主页一个空盒子。所以接下来我们要为每一篇文章增加一个独立的页面来展示其详细内容。

如果我们给每一篇文章增加一个 view 层函数逻辑,然后设置一个独立的 url,那样的话工作太过于繁琐,并且项目的耦合性着实太强,复用性很低。Django 为我们提供了一个很优雅的解决方法,即 动态URL。

我们来修改一下 my_blog/article/views.py 的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from django.shortcuts import render
from django.http import HttpResponse
from article.models import Article
from datetime import datetime
from django.http import Http404

# Create your views here.
def home(request):
post_list = Article.objects.all()
return render(request, 'home.html', {'post_list' : post_list})

def detail(request, my_args):
print(my_args)
post = Article.objects.get(id=int(my_args))
return render(request, 'post.html', {'post': post})

从代码中可以看出,我们需要为 my_args 传入一个 post 的 id。这里我们在 home.html 中实现动态 URL 即可完成我们的需求:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
{% extends "base.html" %}

{% block content %}
<div class="posts">
{% for post in post_list %}
<section class="post">
<header class="post-header">
<h2 class="post-title">{{ post.title }}</h2>

<p class="post-meta">
Time: <a class="post-author" href="#">{{ post.date_time }}</a> <a class="post-category post-category-js" href="#">{{ post.category }}</a>
</p>
</header>

<div class="post-description">
<p>
{{ post.content }}
</p>
<a class="pure-button" href="/{{ post.id }}">
Read More >>>
</a>
</div>
</section>
{% endfor %}
</div><!-- /.blog-post -->
{% endblock %}

然后我们来制作每一篇文章的详情页面。其实和主页的思路很像,我们只需要将对于文章的遍历删除即可完成单篇文章的详情页构建。建立 post.html。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{% extends "base.html" %}

{% block content %}
<div class="posts">
<section class="post">
<header class="post-header">
<h2 class="post-title">{{ post.title }}</h2>
<p class="post-meta">
Time: <a class="post-author" href="#">{{ post.date_time|date:"Y /m /d"}}</a> <a class="post-category post-category-js" href="#">{{ post.category }}</a>
</p>
</header>
<div class="post-description">
<p>
{{ post.content }}
</p>
</div>
</section>
</div><!-- /.blog-post -->
{% endblock %}

为了看出文章列表的效果,我打开 admin 界面再添加一个文章。这时候 http://127.0.0.1:1103/ 查看效果。

返回点击一篇文章的 Read More>> 查看详情按钮,则会看到文章详情页的展示:


我们注意到上方的 URL 部分已经自动将文章的 id 获取出来并实现动态 URL 跳转。