{{ post.title }}
{#striptags用于过滤正文中所有的HTML标签#} {#truncatechars用于截取正文前300个字符#} {{ post.content|striptags|truncatechars:300 }}
PyCharm 2017.3.2 (Professional Edition)
Python 3.6.3
windows 10
Sqlite3
接上文Django2.0笔记(5)-开发个人博客系统(三),本文继续对博客系统进行优化,主要包括:
1. 前端界面美化
2. 文章列表分页
3. 实现文章分类搜索和标签搜索
无图无真相,先上效果图:
1.增加font awesome
字体图标,可以在http://www.fontawesome.com.cn/
网站上下载font-awesome.min.css
文件,并将其放到static/css
目录下,然后在基础模板中引入,页面代码如下:
base.html
{% load static %}
{% block title %} jbt Blog {% endblock %}
{% block content %}
{% endblock %}
可以用 标签把 Font Awesome 图标放在任意位置,图标的大小可以使用
fa-lg (33% 递增)
, fa-2x
, fa-3x
, fa-4x
, fa-5x
或者直接指定font-size
。
2.主页文章列表页也增加Font Awesome 图标,增加文章作者头像,文章之间加入分隔线,还有增加分页,页面代码如下:
home.html
{% extends "base.html" %}
{% load static %}
{% block content %}
{% for post in post_list %}
{{ post.title }}
{#striptags用于过滤正文中所有的HTML标签#}
{#truncatechars用于截取正文前300个字符#}
{{ post.content|striptags|truncatechars:300 }}
{% endfor %}
{% if post_list.object_list and post_list.paginator.num_pages > 1 %}
{% endif %}
{% endblock %}
3.文章详情页增加Font Awesome 图标、分类和标签搜索,页面代码如下:
post.html
{% extends "base.html" %}
{% block content %}
{{ post.title }}
{{ post.content |safe}}
{% endblock %}
4.分类搜索结果页、标签搜索结果页和主页文章列表页结构类似,区别在于文章列表页显示的是没有加筛选条件的结果,分类搜索结果页是显示特定分类的文章列表,标签搜索结果页是显示特定标签的文章列表,分类搜索结果页代码如下:
category.html
{% extends "base.html" %}
{% load static %}
{% block content %}
分类: {{ category }}
{% for post in post_list %}
{{ post.title }}
{#striptags用于过滤正文中所有的HTML标签#}
{#truncatechars用于截取正文前300个字符#}
{{ post.content|striptags|truncatechars:300 }}
{% endfor %}
{% if post_list.object_list and post_list.paginator.num_pages > 1 %}
{% endif %}
{% endblock %}
标签搜索结果页页面代码如下:
tag.html
{% extends "base.html" %}
{% load static %}
{% block content %}
标签: {{ tag }}
{% for post in post_list %}
{{ post.title }}
{#striptags用于过滤正文中所有的HTML标签#}
{#truncatechars用于截取正文前300个字符#}
{{ post.content|striptags|truncatechars:300 }}
{% endfor %}
{% if post_list.object_list and post_list.paginator.num_pages > 1 %}
{% endif %}
{% endblock %}
1.由于前端页面左侧使用文章分类作为菜单,为了在每个页面都能看到菜单,每个视图函数在渲染页面模板的时候都需要传递category_list属性到页面,具体细节看注释,视图函数脚本代码如下:
views.py
from django.shortcuts import render
from apps.blog.models import Article, Category, Tag
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.http import Http404
from django.conf import settings
categories = Category.objects.all() # 获取全部的分类对象
tags = Tag.objects.all() # 获取全部的标签对象
def home(request): # 主页
posts = Article.objects.all() # 获取全部的Article对象
paginator = Paginator(posts, settings.PAGE_NUM) # 每页显示数量
page = request.GET.get('page') # 获取URL中page参数的值
try:
post_list = paginator.page(page)
except PageNotAnInteger:
post_list = paginator.page(1)
except EmptyPage:
post_list = paginator.page(paginator.num_pages)
return render(request, 'home.html', {'post_list': post_list, 'category_list': categories})
def detail(request, id): # 文章详情页
try:
post = Article.objects.get(id=str(id))
post.viewed() # 更新浏览次数
tags = post.tags.all()
except Article.DoesNotExist:
raise Http404
return render(request, 'post.html', {'post': post, 'tags': tags, 'category_list': categories})
def search_category(request, id): # 分类搜索
posts = Article.objects.filter(category_id=str(id))
category = categories.get(id=str(id))
paginator = Paginator(posts, settings.PAGE_NUM) # 每页显示数量
try:
page = request.GET.get('page') # 获取URL中page参数的值
post_list = paginator.page(page)
except PageNotAnInteger:
post_list = paginator.page(1)
except EmptyPage:
post_list = paginator.page(paginator.num_pages)
return render(request, 'category.html', {'post_list': post_list, 'category_list': categories, 'category': category})
def search_tag(request, tag): # 标签搜索
posts = Article.objects.filter(tags__name__contains=tag)
paginator = Paginator(posts, settings.PAGE_NUM) # 每页显示数量
try:
page = request.GET.get('page') # 获取URL中page参数的值
post_list = paginator.page(page)
except Article.DoesNotExist:
raise Http404
except PageNotAnInteger:
post_list = paginator.page(1)
except EmptyPage:
post_list = paginator.page(paginator.num_pages)
return render(request, 'tag.html', {'post_list': post_list, 'category_list': categories, 'tag': tag})
2.为了使页面操作和视图函数绑定,需要添加相应的路由,urls.py
文件代码如下:
urls.py
from django.contrib import admin
from django.urls import path
from apps.blog import views
from django.conf.urls import include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home, name='home'), # 主页
path('home/', views.home, name='home'), # 主页
path('articles//', views.detail, name='detail'), # 文章详情
path('category//', views.search_category, name='category_menu'), # 分类搜索
path('tag//', views.search_tag, name='search_tag'), # 标签搜索
path('summernote/', include('django_summernote.urls')),
path('jet/', include('jet.urls', 'jet')), # Django JET URLS
path('jet/dashboard/', include('jet.dashboard.urls', 'jet-dashboard')), # Django JET dashboard URLS
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
3.配置文件里,这里主要添加了分页参数PAGE_NUM
,设置单页显示多少篇文章,还有就是添加了后台自定义菜单JET_SIDE_MENU_ITEMS
参数,这个参数的解释大家可以看下JET的官方文档[http://jet.readthedocs.io/en/latest/config_file.html#custom-menu
里面有详细说明,目前我们用到的就是菜单排序以及后面要用到的后台添加自定义静态页面,其他的应该没什么了,到目前为止完整的配置文件代码如下:](http://jet.readthedocs.io/en/latest/config_file.html#custom-menu`里面有详细说明,目前我们用到的就是菜单排序以及后面要用到的后台添加自定义静态页面,其他的应该没什么了,到目前为止完整的配置文件代码如下:)
settings.py
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.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '1ek)3z+-*)(&1c&3fv=2*=lr_cyst85w&a4y#5!2m*ik@=&!p0'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'jet.dashboard',
'jet',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'apps.blog',
'django_summernote',
]
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 = 'jbt_blog.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 = 'jbt_blog.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.0/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.0/topics/i18n/
LANGUAGE_CODE = 'zh-hans' # 有改动
TIME_ZONE = 'Asia/Shanghai' # 有改动
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
# 分页配置
PAGE_NUM = 2
# 富文本编辑器设置
SUMMERNOTE_CONFIG = {
# Using SummernoteWidget - iframe mode
'iframe': True, # or set False to use SummernoteInplaceWidget - no iframe mode
# Using Summernote Air-mode
'airMode': False,
# Use native HTML tags (``, ``, ...) instead of style attributes
'styleWithSpan': False,
# Change editor size
'width': '80%',
'height': '480',
# Use proper language setting automatically (default)
'lang': 'zh-CN',
}
# 主题
JET_THEMES = [
{
'theme': 'default', # theme folder name
'color': '#47bac1', # color of the theme's button in user menu
'title': 'Default' # theme title
},
{
'theme': 'green',
'color': '#44b78b',
'title': 'Green'
},
{
'theme': 'light-green',
'color': '#2faa60',
'title': 'Light Green'
},
{
'theme': 'light-violet',
'color': '#a464c4',
'title': 'Light Violet'
},
{
'theme': 'light-blue',
'color': '#5EADDE',
'title': 'Light Blue'
},
{
'theme': 'light-gray',
'color': '#222',
'title': 'Light Gray'
}
]
# 是否展开所有菜单
JET_SIDE_MENU_COMPACT = True # 菜单不是很多时建议为TRUE
JET_SIDE_MENU_ITEMS = [ # A list of application or custom item dicts
{'label': '内容管理', 'app_label': 'blog', 'items': [
{'name': 'article'},
{'name': 'tag'},
{'name': 'category'},
]},
{'label': '附件管理', 'app_label': 'django_summernote', 'items': [
{'label': '附件列表', 'name': 'attachment'},
]},
{'label': '权限管理', 'items': [
{'name': 'auth.user', 'permissions': ['auth.user']},
{'name': 'auth.group', 'permissions': ['auth.user']},
]},
]
以上步骤完成以后重启开发服务器,查看页面显示结果。
全部代码已分享至Github:https://github.com/leeyis/jbt_blog
有账户的不妨star一下啦~