Django : 6 — 自定義URL & 分頁

Django

自定義 url

常常看到很多網址後面會接上年/月/日等等的資訊,在 Django 也是可以自定義 URL 的

urls.py

1
2
3
4
5
6
7
8
9
10
11
12
13
## project/blog/urls.py
app_name = 'blog'
urlpatterns = [
path('', views.list, name='list'),
path('author', views.author),
path(
'<int:year>/<int:month>/<int:day>/<str:slug>/',
views.detail,
name='detail'
),
path('testing/', views.testing, name='testing'),

]

首先先到 urls 定義路徑的顯示方式,這裡定義為<int:year>/<int:month>/<int:day>/<str:slug>/

model.py

1
2
3
4
5
6
7
8
9
10
11
12
from django.urls import reverse

def get_url(self):
return reverse(
'blog:detail',
args=[
self.published_date.year,
self.published_date.month,
self.published_date.day,
self.slug
]
)

urls.py定義了好路徑,需要將資料傳入資料,此時可以使用reverse 將值傳給urls.py

list.html

1
2
3
4
5
#project/blog/templates/blog/list.html

<a href="{{ post.get_url }}">
{{ post.title }}
</a>

這時前台就能夠在文章標題上加上路徑了~


分頁

Views.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#project/blog/views.py
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

def list(request):
posts = Post.objects.all()
paginator = Paginator(posts, 3) #每頁三篇
page = request.GET.get('page')
try:
posts = paginator.page(page) #返回第幾頁
except PageNotAnInteger:
posts = paginator.page(1)#傳入不是整數,返回第一頁
except EmptyPage: #傳入的數太大
posts = paginator.page(paginator.num_pages) #取最後一頁的紀錄
return render(
request,
'blog/list.html',
{'posts': posts} #把post返回template
)

list.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# project/blog/templates/blog/list.html
<div>
<span>
{% if posts.has_previous %}
<a href="?page{{ posts.previous_page_number }}">Previous</a>
{% endif %}
</span>
<span>
Page {{ posts.number }} of {{ posts.paginator.num_pages }}.
</span>
<span>
{% if posts.has_next %}
<a href="?page={{ posts.next_page_number }}">Next</a>
{% endif %}
</span>
</div>

這時就會出現分頁符號了~

本篇文章是我由以下參考資料整理+自己繪圖而成,如果您有興趣了解更多,請參考:

參考資料:

Django Docs - paginator

评论