django快速做一个博客项目(3)

11实现文章详情页面的跳转

设计文章详情页url–>完善视图函数逻辑–>实现首页跳转

11.1设计文章详情页url

/blog/detail >不能指定某一篇博客。
需要重新规划
/blog/detail/1
>指定第一篇博客。
/blog/detail/2==>指定第2篇博客。
/blog/detail/3==>指定第3篇博客。
在blog/urls.py中修改如下:

from django.urls import path
import blog.views

urlpatterns = [
    path('content', blog.views.article_content),
    path('index', blog.views.get_index_page),
    # path('detail', blog.views.get_detail_page),
    path('detail/', blog.views.get_detail_page),
]

blog下views.py中修改get_detail_page如下:

def get_detail_page(request, article_id):
    all_article = Article.objects.all()
    curr_article = None
    for article in all_article:
        if article.article_id == article_id:
            curr_article = article
            break
    section_list = curr_article.content.split('\n')
    return render(request, 'blog/detail.html',
                  {
     
                      'curr_article': curr_article,
                      'section_list': section_list
                   })

python manage.py runserver运行项目分别输入查看
http://127.0.0.1:8000/blog/detail/1
http://127.0.0.1:8000/blog/detail/2
django快速做一个博客项目(3)_第1张图片
修改index.html中这两行,加入a标签,就可以实现跳转

<h2><a href="/blog/detail/{
      { article.article_id }}">{
    { article.title }}a>h2>
<h4><a href="/blog/detail/{
      { article.article_id }}">{
    { article.title }}a>h4>

12 实现上下文章跳转

12.1detail.html中最下面的入上一篇,下一篇,

bootstrap组件里分页翻页

https://v3.bootcss.com/components/#pagination-pager

<div>
    <nav aria-label="...">
        <ul class="pager">
            <li><a href="/blog/detail/{
      { previous_article.article_id }}">上一篇:{
    { previous_article.title }}a>li>
            <li><a href="/blog/detail/{
      { next_article.article_id }}">下一篇:{
    { next_article.title }}a>li>
        ul>
    nav>
div>

放在最下面,body上面。然后http://127.0.0.1:8000/blog/detail/1
django快速做一个博客项目(3)_第2张图片

12.1修改视图函数

def get_detail_page(request, article_id):
    all_article = Article.objects.all()
    curr_article = None
    previous_index = 0
    next_index = 0
    previous_article = None
    next_article = None
    for index, article in enumerate(all_article):
        if index == 0:
            previous_index = 0
            next_index = index + 1
        if index == len(all_article) - 1:
            previous_index = index - 1
            next_index = index
        else:
            previous_index = index - 1
            next_index = index + 1

        if article.article_id == article_id:
            curr_article = article
            previous_article = all_article[previous_index]
            next_article = all_article[next_index]
            break
    section_list = curr_article.content.split('\n')
    return render(request, 'blog/detail.html',
                  {
     
                      'curr_article': curr_article,
                      'section_list': section_list,
                      'previous_article': previous_article,
                      'next_article': next_article
                  })

就实现上下篇切换了。

你可能感兴趣的