博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
搭建自己的博客(十一):添加根据日期筛选
阅读量:5153 次
发布时间:2019-06-13

本文共 11847 字,大约阅读时间需要 39 分钟。

之前有通过分类来筛选文章的功能,这次添加根据创建日期来筛选文章。

1、变化的部分

2、上代码

ul.blog-types,ul.blog-dates {
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 header_extends %}    
{% endblock %}{# 标题 #}{% block title %} {
{ blog.title }}{% endblock %}{# 内容#}{% block content %}

    {
    { blog.title }}

  • 作者:{
    { blog.author }}
  • {# 时间过滤器让时间按照自己需要的格式过滤 #}
  • 发布日期:{
    { blog.created_time|date:"Y-m-d H:n:s" }}
  • 分类: { { blog.blog_type }}

{

{ blog.content }}

上一篇: {% if previous_blog %} {

{ previous_blog.title }} {% else %} 没有了 {% endif %}

下一篇: {% if next_blog %} {

{ next_blog.title }} {% else %} 没有了 {% endif %}

{% endblock %}{% block js %} {% endblock %}
blog_detail.html
{% extends 'base.html' %}{% load staticfiles %}{# 标题 #}{% block title %}    felix Blog{% endblock %}{% block header_extends %}    
{% endblock %}{# 内容#}{% block content %}
{% block blog_type_title %}博客列表{% endblock %}
{% for blog in blogs %}

{ { blog.title }}

{# 添加图标 #} { { blog.blog_type }} { { blog.created_time|date:"Y-m-d" }}

{ { blog.content|truncatechars:30 }}

{% empty %}

--暂无博客,敬请期待--

{% endfor %}
{# 分页 #}
    {# 首页 #}
  • 首页
  • {# 上一页 #} {% if page_of_blogs.has_previous %}
  • 上一页
  • {% else %}
  • 上一页
  • {% endif %} {# 全部页码 #} {% for page_num in page_range %} {# 添加当前页高亮显示 #} {% if page_num == page_of_blogs.number %}
  • { { page_num }}
  • {% else %}
  • { { page_num }}
  • {% endif %} {% endfor %} {# 下一页 #} {% if page_of_blogs.has_next %}
  • 下一页
  • {% else %}
  • 下一页
  • {% endif %} {# 尾页 #}
  • 尾页

一共有 {

{ page_of_blogs.paginator.count }}篇博客,当前{
{ page_of_blogs.number }}页,共{
{ page_of_blogs.paginator.num_pages }}页

博客分类
日期归档
{% endblock %}{% block js %} {% endblock %}
blog_list.html
{% extends 'blog/blog_list.html' %}{# 标题 #}{% block title %}    {
{ blog_type.type_name }}{% endblock %}{% block blog_type_title %} 日期:{
{ blogs_with_date }}{% endblock %}
blog_with_date.html
# -*- coding: utf-8 -*-# @Time    : 18-11-4 下午5:22# @Author  : Felix Wangfrom django.urls import pathfrom . import viewsurlpatterns = [    path('', views.blog_list, name='blog_list'),    # name 表示别名    path('
', views.blog_detail, name='blog_detail'), # 链接非常容易混掉,所以要区分,在链接前面添加type path('type/
', views.blogs_with_type, name='blogs_with_type'), # 根据日期分类 path('date/
/
', views.blogs_with_date, name='blogs_with_date'),]
urls.py
from django.shortcuts import render_to_response, get_object_or_404from .models import Blog, BlogTypefrom django.core.paginator import Paginatorfrom django.conf import settings# 分页部分公共代码def blog_list_common_data(requests, blogs_all_list):    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)))  # 获取需要显示的页码 并且剔除不符合条件的页码    return {        'blogs': page_of_blogs.object_list,        'page_of_blogs': page_of_blogs,        'blog_types': BlogType.objects.all(),        'page_range': page_range,        'blog_dates': Blog.objects.dates('created_time', 'month', order='DESC')    }# 博客列表def blog_list(requests):    blogs_all_list = Blog.objects.all()  # 获取全部博客    context = blog_list_common_data(requests, blogs_all_list)    return render_to_response('blog/blog_list.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)  # 获取全部博客    context = blog_list_common_data(requests, blogs_all_list)    context['blog_type'] = blog_type    return render_to_response('blog/blog_with_type.html', context)# 根据日期筛选def blogs_with_date(requests, year, month):    blogs_all_list = Blog.objects.filter(created_time__year=year, created_time__month=month)  # 获取全部博客    context = blog_list_common_data(requests, blogs_all_list)    context['blogs_with_date'] = '{}年{}日'.format(year, month)    return render_to_response('blog/blog_with_date.html', context)# 博客详情def blog_detail(requests, blog_pk):    blog = get_object_or_404(Blog, pk=blog_pk)    context = {        'blog': blog,        'previous_blog': Blog.objects.filter(created_time__gt=blog.created_time).last(),        'next_blog': Blog.objects.filter(created_time__lt=blog.created_time).first(),    }    return render_to_response('blog/blog_detail.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, seehttps://docs.djangoproject.com/en/2.1/topics/settings/For the full list of settings and their values, seehttps://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 = TrueALLOWED_HOSTS = []# Application definitionINSTALLED_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/#databasesDATABASES = {    # '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-validatorsAUTH_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 = TrueUSE_L10N = True# 不考虑时区USE_TZ = False# 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.py

3、注意点

(1)、django通过月份查询时可能会遇到无法查询到内容的问题。

可以在settings中设置

# 不考虑时区USE_TZ = False

用来不考虑时区

(2)、django中的查询扩展

 

转载于:https://www.cnblogs.com/felixwang2/p/9962791.html

你可能感兴趣的文章
Oracle中的instead of触发器
查看>>
【bzoj2788】Festival
查看>>
执行gem install dryrun错误
查看>>
Java SE之正则表达式一:概述
查看>>
HTML5简单入门系列(四)
查看>>
实现字符串反转
查看>>
转载:《TypeScript 中文入门教程》 5、命名空间和模块
查看>>
苹果开发中常用英语单词
查看>>
[USACO 1.4.3]等差数列
查看>>
Shader Overview
查看>>
Reveal 配置与使用
查看>>
Java中反射的学习与理解(一)
查看>>
nginx配置socket服务
查看>>
C语言初学 俩数相除问题
查看>>
B/S和C/S架构的区别
查看>>
[Java] Java record
查看>>
jQuery - 控制元素显示、隐藏、切换、滑动的方法
查看>>
postgresql学习文档
查看>>
Struts2返回JSON数据的具体应用范例
查看>>
js深度克隆对象、数组
查看>>