自定義 url
常常看到很多網址後面會接上年/月/日等等的資訊,在 Django 也是可以自定義 URL 的
urls.py
1 2 3 4 5 6 7 8 9 10 11 12 13
| 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
|
<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
| 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} )
|
list.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <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
评论