码迷,mamicode.com
首页 > 其他好文 > 详细

搭建自己的博客(十):优化分页功能

时间:2018-11-15 21:12:13      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:nvm   wadl   bmp   comm   oar   mys   ++   vmm   time   

上一篇简单的添加了分页功能,但是感觉太粗糙了,这篇优化分页功能。

1、变化的内容

技术分享图片

2、上代码

技术分享图片
ul.blog-types {
    list-style-type: none;
}

div.blog:not(:last-child) {
    margin-bottom: 2em;
    padding-bottom: 1em;
    border-bottom: 1px solid #eee;
}

div.blog h3 {
    margin-top: 0.5em;
}

div.blog-info p {
    margin-bottom: 0;
}

div.blog-info-description {
    list-style-type: none;
    margin-bottom: 1em;
}

ul.blog-info-description li {
    display: inline-block;
    margin-right: 2em;
}

div.blog-content {
    text-indent: 2em;
}

div.paginator {
    text-align: center;
}

div.container {
    max-width: 80%;
}
blog.css
技术分享图片
{% extends ‘base.html‘ %}
{% load staticfiles %}
{# 标题 #}
{% block title %}
    felix Blog
{% endblock %}

{% block header_extends %}
    <link rel="stylesheet" href="{% static ‘blog/blog.css‘ %}">
    <link rel="stylesheet" href="{% static ‘fontawesome-free-5.5.0-web/css/all.min.css‘ %}">
{% endblock %}

{# 内容#}
{% block content %}
    <div class="container">
        <div class="row">
            <div class="col-md-8">
                <div class="card" style="">
                    <div class="card-header"><h5 class="card-title">{% block blog_type_title %}博客列表{% endblock %}</h5>
                    </div>
                    <div class="card-body">
                        {% for blog in blogs %}
                            <div class="blog">
                                <h3><a href="{% url ‘blog_detail‘ blog.pk %}">{{ blog.title }}</a></h3>
                                <div class="blog-info">
                                    <p>
                                        {# 添加图标 #}
                                        <i class="fas fa-tag"></i>
                                        <a href="{% url ‘blogs_with_type‘ blog.blog_type.pk %}">
                                            {{ blog.blog_type }}
                                        </a>
                                        <i class="far fa-clock  "></i>
                                        {{ blog.created_time|date:"Y-m-d" }}
                                    <p>
                                </div>
                                <p>{{ blog.content|truncatechars:30 }}</p>
                            </div>
                        {% empty %}
                            <div class="blog">
                                <h3>--暂无博客,敬请期待--</h3>
                            </div>
                        {% endfor %}
                    </div>
                </div>

                {# 分页 #}
                <div class="paginator">
                    <ul class="pagination justify-content-center">
                        {# 首页 #}
                        <li class="page-item"><a class="page-link" href="?page=1">首页</a></li>
                        {# 上一页 #}
                        {% if page_of_blogs.has_previous %}
                            <li class="page-item"><a class="page-link"
                                                     href="?page={{ page_of_blogs.previous_page_number }}">上一页</a>
                            </li>
                        {% else %}
                            <li class="page-item disabled"><span class="page-link">上一页</span></li>
                        {% endif %}
                        {# 全部页码 #}
                        {% for page_num in page_range %}
                            {# 添加当前页高亮显示 #}
                            {% if page_num == page_of_blogs.number %}
                                <li class="page-item active"><span class="page-link">{{ page_num }}</span></li>
                            {% else %}
                                <li class="page-item"><a class="page-link"
                                                         href="?page={{ page_num }}">{{ page_num }}</a></li>
                            {% endif %}
                        {% endfor %}
                        {# 下一页 #}
                        {% if page_of_blogs.has_next %}
                            <li class="page-item"><a class="page-link"
                                                     href="?page={{ page_of_blogs.next_page_number }}">下一页</a></li>
                        {% else %}
                            <li class="page-item disabled"><span class="page-link">下一页</span></li>
                        {% endif %}
                        {# 尾页 #}
                        <li class="page-item"><a class="page-link"
                                                 href="?page={{ page_of_blogs.paginator.num_pages }}">尾页</a></li>
                    </ul>

                    <p>
                        一共有 {{ page_of_blogs.paginator.count }}篇博客,当前{{ page_of_blogs.number }}页,共{{ page_of_blogs.paginator.num_pages }}页
                    </p>

                </div>
            </div>

            <div class="col-md-4">
                <div class="card" style="">
                    <div class="card-header"><h5 class="card-title">博客分类</h5></div>
                    <div class="card-body">
                        <ul class="blog-types">
                            {% for blog_type in blog_types %}
                                <li><a href="{% url ‘blogs_with_type‘ blog_type.pk %}">{{ blog_type.type_name }}</a>
                                </li>
                            {% empty %}
                                <li>暂无分类</li>
                            {% endfor %}
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>

{% endblock %}

{% block js %}
    <script>
        $(".nav-blog").addClass("active").siblings().removeClass("active");
    </script>
{% endblock %}
blog_list.html
技术分享图片
{% extends ‘blog/blog_list.html‘ %}

{# 标题 #}
{% block title %}
    {{ blog_type.type_name }}
{% endblock %}

{% block blog_type_title %}
    分类:{{ blog_type.type_name }}
{% endblock %}
blog_with_type.html
技术分享图片
from django.shortcuts import render_to_response, get_object_or_404
from .models import Blog, BlogType
from django.core.paginator import Paginator
from django.conf import settings

# Create your views here.

# 博客列表
def blog_list(requests):
    # 分页
    blogs_all_list = Blog.objects.all()  # 获取全部博客
    paginator = Paginator(blogs_all_list, settings.EACH_PAGE_BLOGS_NUMBER)  # 第一个参数是全部内容,第二个是每页多少
    page_num = requests.GET.get(‘page‘, 1)  # 获取url的页面参数(get请求)
    page_of_blogs = paginator.get_page(page_num)  # 从分页器中获取指定页码的内容

    current_page_num = page_of_blogs.number  # 获取当前页
    all_pages = paginator.num_pages
    if all_pages < 5:
        page_range = list(
            range(max(current_page_num - 2, 1),
                  min(all_pages + 1, current_page_num + 3)))  # 获取需要显示的页码 并且剔除不符合条件的页码
    else:
        if current_page_num <= 2:
            page_range = range(1, 5 + 1)
        elif current_page_num >= all_pages - 2:
            page_range = range(all_pages - 4, paginator.num_pages + 1)
        else:
            page_range = list(
                range(max(current_page_num - 2, 1),
                      min(all_pages + 1, current_page_num + 3)))  # 获取需要显示的页码 并且剔除不符合条件的页码

    context = {
        ‘blogs‘: page_of_blogs.object_list,
        ‘page_of_blogs‘: page_of_blogs,
        ‘blog_types‘: BlogType.objects.all(),
        ‘page_range‘: page_range,
    }
    return render_to_response(‘blog/blog_list.html‘, context)


# 博客详情
def blog_detail(requests, blog_pk):
    context = {
        ‘blog‘: get_object_or_404(Blog, pk=blog_pk)
    }

    return render_to_response(‘blog/blog_detail.html‘, context)


def blogs_with_type(requests, blog_type_pk):
    blog_type = get_object_or_404(BlogType, pk=blog_type_pk)
    # 分页
    blogs_all_list = Blog.objects.filter(blog_type=blog_type)  # 获取全部博客
    paginator = Paginator(blogs_all_list, settings.EACH_PAGE_BLOGS_NUMBER)  # 第一个参数是全部内容,第二个是每页多少
    page_num = requests.GET.get(‘page‘, 1)  # 获取url的页面参数(get请求)
    page_of_blogs = paginator.get_page(page_num)  # 从分页器中获取指定页码的内容

    current_page_num = page_of_blogs.number  # 获取当前页
    all_pages = paginator.num_pages
    if all_pages < 5:
        page_range = list(
            range(max(current_page_num - 2, 1),
                  min(all_pages + 1, current_page_num + 3)))  # 获取需要显示的页码 并且剔除不符合条件的页码
    else:
        if current_page_num <= 2:
            page_range = range(1, 5 + 1)
        elif current_page_num >= all_pages - 2:
            page_range = range(all_pages - 4, paginator.num_pages + 1)
        else:
            page_range = list(
                range(max(current_page_num - 2, 1),
                      min(all_pages + 1, current_page_num + 3)))  # 获取需要显示的页码 并且剔除不符合条件的页码

    context = {
        ‘blogs‘: page_of_blogs.object_list,
        ‘page_of_blogs‘: page_of_blogs,
        ‘blog_types‘: BlogType.objects.all(),
        ‘page_range‘: page_range,
        ‘blog_type‘: blog_type,
    }

    return render_to_response(‘blog/blog_with_type.html‘, context)
views.py
技术分享图片
"""
Django settings for myblog project.

Generated by ‘django-admin startproject‘ using Django 2.1.3.

For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ‘ea+kzo_5k^6r7micfg@lar1(rfdc08@b4*+w5d11=0mp1p5ngr‘

# SECURITY WARNING: don‘t run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    ‘django.contrib.admin‘,
    ‘django.contrib.auth‘,
    ‘django.contrib.contenttypes‘,
    ‘django.contrib.sessions‘,
    ‘django.contrib.messages‘,
    ‘django.contrib.staticfiles‘,
    ‘blog.apps.BlogConfig‘,  # 将自己创建的app添加到设置中
]

MIDDLEWARE = [
    ‘django.middleware.security.SecurityMiddleware‘,
    ‘django.contrib.sessions.middleware.SessionMiddleware‘,
    ‘django.middleware.common.CommonMiddleware‘,
    ‘django.middleware.csrf.CsrfViewMiddleware‘,
    ‘django.contrib.auth.middleware.AuthenticationMiddleware‘,
    ‘django.contrib.messages.middleware.MessageMiddleware‘,
    ‘django.middleware.clickjacking.XFrameOptionsMiddleware‘,
]

ROOT_URLCONF = ‘myblog.urls‘

TEMPLATES = [
    {
        ‘BACKEND‘: ‘django.template.backends.django.DjangoTemplates‘,
        ‘DIRS‘: [
            os.path.join(BASE_DIR, ‘templates‘),
        ],
        ‘APP_DIRS‘: True,
        ‘OPTIONS‘: {
            ‘context_processors‘: [
                ‘django.template.context_processors.debug‘,
                ‘django.template.context_processors.request‘,
                ‘django.contrib.auth.context_processors.auth‘,
                ‘django.contrib.messages.context_processors.messages‘,
            ],
        },
    },
]

WSGI_APPLICATION = ‘myblog.wsgi.application‘

# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = {
    # ‘default‘: {
    #     ‘ENGINE‘: ‘django.db.backends.sqlite3‘,
    #     ‘NAME‘: os.path.join(BASE_DIR, ‘db.sqlite3‘),
    # }
    ‘default‘: {
        ‘ENGINE‘: ‘django.db.backends.mysql‘,
        ‘NAME‘: ‘myblogs‘,  # 要连接的数据库,连接前需要创建好
        ‘USER‘: ‘root‘,  # 连接数据库的用户名
        ‘PASSWORD‘: ‘felixwang‘,  # 连接数据库的密码
        ‘HOST‘: ‘127.0.0.1‘,  # 连接主机,默认本级
        ‘PORT‘: 3306  # 端口 默认3306
    }
}

# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        ‘NAME‘: ‘django.contrib.auth.password_validation.UserAttributeSimilarityValidator‘,
    },
    {
        ‘NAME‘: ‘django.contrib.auth.password_validation.MinimumLengthValidator‘,
    },
    {
        ‘NAME‘: ‘django.contrib.auth.password_validation.CommonPasswordValidator‘,
    },
    {
        ‘NAME‘: ‘django.contrib.auth.password_validation.NumericPasswordValidator‘,
    },
]

# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

# LANGUAGE_CODE = ‘en-us‘
LANGUAGE_CODE = ‘zh-hans‘

# TIME_ZONE = ‘UTC‘
TIME_ZONE = ‘Asia/Shanghai‘

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = ‘/static/‘
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static")
]


# 自定义参数
EACH_PAGE_BLOGS_NUMBER=7
settings

3、注意点

有时候我们需要用到全局变量,可以放在settings.py文件中,然后通过from django.conf import settings调用

搭建自己的博客(十):优化分页功能

标签:nvm   wadl   bmp   comm   oar   mys   ++   vmm   time   

原文地址:https://www.cnblogs.com/felixwang2/p/9961862.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!