開發(fā)環(huán)境
PyCharm 2017.3.2 (Professional Edition)
Python 3.6.3
windows 10
Sqlite3
本文目標(biāo)
接上文Django2.0筆記(5)-開發(fā)個人博客系統(tǒng)(三)钳垮,本文繼續(xù)對博客系統(tǒng)進(jìn)行優(yōu)化,主要包括:
1. 前端界面美化
2. 文章列表分頁
3. 實現(xiàn)文章分類搜索和標(biāo)簽搜索
無圖無真相额港,先上效果圖:
開發(fā)過程
前端頁面
1.增加font awesome
字體圖標(biāo)饺窿,可以在http://www.fontawesome.com.cn/
網(wǎng)站上下載font-awesome.min.css
文件,并將其放到static/css
目錄下移斩,然后在基礎(chǔ)模板中引入肚医,頁面代碼如下:
base.html
<!DOCTYPE html>
{% load static %}
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %} jbt Blog {% endblock %}</title>
<link rel="stylesheet" type="text/css" href="{% static 'css/pure-min.css' %}"/>
<link rel="stylesheet" type="text/css" href="{% static 'css/grids-responsive-min.css' %}"/>
<link rel="stylesheet" type="text/css" href="{% static 'css/blog.css' %}"/>
<link rel="stylesheet" type="text/css" href="{% static 'css/font-awesome.min.css' %}"/>
</head>
<body>
<div id="layout" class="pure-g">
<div class="sidebar pure-u-1 pure-u-md-1-4">
<div class="header" style="text-align: center">
<h1 class="brand-title"><a href="{% url 'home' %}" style="text-decoration: none">金筆頭博客</a></h1>
<h2 class="brand-tagline">Love Learning, Love Sharing...</h2>
<nav class="nav">
<ul class="nav-list">
<li class="nav-item">
{% for category in category_list %}
<a class="pure-button" href="{% url 'category_menu' id=category.id %}" style="text-decoration: none">{{ category }}</a>
{% endfor %}
</li>
</ul>
<br>
<ul class="nav-list">
<li>
<a href="#" style="text-decoration: none">
<i class="fa fa-weixin" style="font-size: 30px" aria-hidden="true" title="微信公眾號"></i>
</a>
<a href=mailto:jinbitou@126.com style="text-decoration: none">
<i class="fa fa-envelope-o" style="font-size: 30px" aria-hidden="true" title="郵箱"></i>
</a>
<a style="text-decoration: none" title="Github">
<i class="fa fa-github" style="font-size: 34px" aria-hidden="true"></i>
</a>
</li>
</ul>
</nav>
</div>
</div>
<div class="content pure-u-1 pure-u-md-3-4">
<div>
{% block content %}
{% endblock %}
</div>
</div>
</div>
</body>
</html>
可以用 <i>
標(biāo)簽把 Font Awesome 圖標(biāo)放在任意位置,圖標(biāo)的大小可以使用fa-lg (33% 遞增)
, fa-2x
, fa-3x
, fa-4x
, fa-5x
或者直接指定font-size
向瓷。
2.主頁文章列表頁也增加Font Awesome 圖標(biāo)肠套,增加文章作者頭像,文章之間加入分隔線猖任,還有增加分頁你稚,頁面代碼如下:
home.html
{% extends "base.html" %}
{% load static %}
{% block content %}
<div class="posts">
{% for post in post_list %}
<section class="post">
<header class="post-header">
<img width="48" height="48" alt="Tilo Mitra's avatar" class="post-avatar" src='{% static "image/avatar.png" %}'>
<h2 class="post-title"><a href="{% url 'detail' id=post.id %}" style="text-decoration: none">{{ post.title }}</a></h2>
<p class="post-meta">
<i class="fa fa-calendar" aria-hidden="true"></i> {{ post.pub_time |date:'Y-m-d'}}
<i class="fa fa-eye" aria-hidden="true"></i> {{ post.views }}次瀏覽
</p>
</header>
<div class="post-description">
<p>
{#striptags用于過濾正文中所有的HTML標(biāo)簽#}
{#truncatechars用于截取正文前300個字符#}
{{ post.content|striptags|truncatechars:300 }}
</p>
</div>
<div>
<a class="post-category post-category-design" href="{% url 'detail' id=post.id %}" style="text-decoration: none">閱讀全文</a>
</div>
<h1 class="content-subhead"></h1>
</section>
{% endfor %}
</div><!-- /.blog-post -->
{% if post_list.object_list and post_list.paginator.num_pages > 1 %}
<div>
{% if post_list.has_previous %}
<a class="footer" href="?page={{ post_list.previous_page_number }}" style="text-decoration: none; float: left;">
<i class="fa fa-angle-left"></i> 上一頁
</a>
{% endif %}
{% if post_list.has_next %}
<a class="footer" href="?page={{ post_list.next_page_number }}" style="text-decoration: none; float: right;">
下一頁 <i class="fa fa-angle-right"></i>
</a>
{% endif %}
</div>
{% endif %}
{% endblock %}
3.文章詳情頁增加Font Awesome 圖標(biāo)、分類和標(biāo)簽搜索朱躺,頁面代碼如下:
post.html
{% extends "base.html" %}
{% block content %}
<div class="posts">
<section class="post">
<header class="post-header">
<h2 class="post-title">{{ post.title }}</h2>
<p class="post-meta">
<i class="fa fa-clock-o" aria-hidden="true"></i> {{ post.pub_time|date:'Y-m-d H:m:s'}}
<i class="fa fa-list-alt"></i> <a class="post-category post-category-pure" href="{% url 'category_menu' id=post.category_id %}" style="text-decoration: none">{{ post.category }}</a>
<i class="fa fa-tags" aria-hidden="true"></i>
{% for tag in tags %}
<a class="post-category post-category-pure" href="{% url 'search_tag' tag=tag %}" style="text-decoration: none">{{ tag }}</a>
{% endfor %}
<i class="fa fa-eye" aria-hidden="true"></i> {{ post.views }}次瀏覽
</p>
</header>
<div class="post-description">
<p>
{{ post.content |safe}}
</p>
</div>
</section>
</div><!-- /.blog-post -->
{% endblock %}
4.分類搜索結(jié)果頁刁赖、標(biāo)簽搜索結(jié)果頁和主頁文章列表頁結(jié)構(gòu)類似,區(qū)別在于文章列表頁顯示的是沒有加篩選條件的結(jié)果长搀,分類搜索結(jié)果頁是顯示特定分類的文章列表宇弛,標(biāo)簽搜索結(jié)果頁是顯示特定標(biāo)簽的文章列表,分類搜索結(jié)果頁代碼如下:
category.html
{% extends "base.html" %}
{% load static %}
{% block content %}
<h1 class="content-subhead">分類: <span>{{ category }}</span><br><br></h1>
<div class="blog-post">
{% for post in post_list %}
<section class="post">
<header class="post-header">
<img width="48" height="48" alt="Tilo Mitra's avatar" class="post-avatar" src='{% static "image/avatar.png" %}'>
<h2 class="post-title"><a href="{% url 'detail' id=post.id %}" style="text-decoration: none">{{ post.title }}</a></h2>
<p class="post-meta">
<i class="fa fa-calendar" aria-hidden="true"></i> {{ post.pub_time |date:'Y-m-d'}}
<i class="fa fa-eye" aria-hidden="true"></i> {{ post.views }}次瀏覽
</p>
</header>
<div class="post-description">
<p>
{#striptags用于過濾正文中所有的HTML標(biāo)簽#}
{#truncatechars用于截取正文前300個字符#}
{{ post.content|striptags|truncatechars:300 }}
</p>
</div>
<div>
<a class="post-category post-category-design" href="{% url 'detail' id=post.id %}" style="text-decoration: none">閱讀全文</a>
</div>
<h1 class="content-subhead"></h1>
</section>
{% endfor %}
</div><!-- /.blog-post -->
{% if post_list.object_list and post_list.paginator.num_pages > 1 %}
<div>
{% if post_list.has_previous %}
<a class="footer" href="?page={{ post_list.previous_page_number }}" style="text-decoration: none; float: left;">
<i class="fa fa-angle-left"></i> 上一頁
</a>
{% endif %}
{% if post_list.has_next %}
<a class="footer" href="?page={{ post_list.next_page_number }}" style="text-decoration: none; float: right;">
下一頁 <i class="fa fa-angle-right"></i>
</a>
{% endif %}
</div>
{% endif %}
{% endblock %}
標(biāo)簽搜索結(jié)果頁頁面代碼如下:
tag.html
{% extends "base.html" %}
{% load static %}
{% block content %}
<h1 class="content-subhead">標(biāo)簽: <span>{{ tag }}</span><br><br></h1>
<div class="blog-post">
{% for post in post_list %}
<section class="post">
<header class="post-header">
<img width="48" height="48" alt="Tilo Mitra's avatar" class="post-avatar" src='{% static "image/avatar.png" %}'>
<h2 class="post-title"><a href="{% url 'detail' id=post.id %}" style="text-decoration: none">{{ post.title }}</a></h2>
<p class="post-meta">
<i class="fa fa-calendar" aria-hidden="true"></i> {{ post.pub_time |date:'Y-m-d'}}
<i class="fa fa-eye" aria-hidden="true"></i> {{ post.views }}次瀏覽
</p>
</header>
<div class="post-description">
<p>
{#striptags用于過濾正文中所有的HTML標(biāo)簽#}
{#truncatechars用于截取正文前300個字符#}
{{ post.content|striptags|truncatechars:300 }}
</p>
</div>
<div>
<a class="post-category post-category-design" href="{% url 'detail' id=post.id %}" style="text-decoration: none">閱讀全文</a>
</div>
<h1 class="content-subhead"></h1>
</section>
{% endfor %}
</div><!-- /.blog-post -->
{% if post_list.object_list and post_list.paginator.num_pages > 1 %}
<div>
{% if post_list.has_previous %}
<a class="footer" href="?page={{ post_list.previous_page_number }}" style="text-decoration: none; float: left;">
<i class="fa fa-angle-left"></i> 上一頁
</a>
{% endif %}
{% if post_list.has_next %}
<a class="footer" href="?page={{ post_list.next_page_number }}" style="text-decoration: none; float: right;">
下一頁 <i class="fa fa-angle-right"></i>
</a>
{% endif %}
</div>
{% endif %}
{% endblock %}
后端代碼
1.由于前端頁面左側(cè)使用文章分類作為菜單源请,為了在每個頁面都能看到菜單枪芒,每個視圖函數(shù)在渲染頁面模板的時候都需要傳遞category_list屬性到頁面彻况,具體細(xì)節(jié)看注釋,視圖函數(shù)腳本代碼如下:
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() # 獲取全部的標(biāo)簽對象
def home(request): # 主頁
posts = Article.objects.all() # 獲取全部的Article對象
paginator = Paginator(posts, settings.PAGE_NUM) # 每頁顯示數(shù)量
page = request.GET.get('page') # 獲取URL中page參數(shù)的值
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() # 更新瀏覽次數(shù)
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) # 每頁顯示數(shù)量
try:
page = request.GET.get('page') # 獲取URL中page參數(shù)的值
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): # 標(biāo)簽搜索
posts = Article.objects.filter(tags__name__contains=tag)
paginator = Paginator(posts, settings.PAGE_NUM) # 每頁顯示數(shù)量
try:
page = request.GET.get('page') # 獲取URL中page參數(shù)的值
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.為了使頁面操作和視圖函數(shù)綁定舅踪,需要添加相應(yīng)的路由纽甘,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/<int:id>/', views.detail, name='detail'), # 文章詳情
path('category/<int:id>/', views.search_category, name='category_menu'), # 分類搜索
path('tag/<str:tag>/', views.search_tag, name='search_tag'), # 標(biāo)簽搜索
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.配置文件里,這里主要添加了分頁參數(shù)PAGE_NUM
硫朦,設(shè)置單頁顯示多少篇文章贷腕,還有就是添加了后臺自定義菜單JET_SIDE_MENU_ITEMS
參數(shù),這個參數(shù)的解釋大家可以看下JET的官方文檔[http://jet.readthedocs.io/en/latest/config_file.html#custom-menu
里面有詳細(xì)說明咬展,目前我們用到的就是菜單排序以及后面要用到的后臺添加自定義靜態(tài)頁面,其他的應(yīng)該沒什么了瞒斩,到目前為止完整的配置文件代碼如下:](http://jet.readthedocs.io/en/latest/config_file.html#custom-menu`里面有詳細(xì)說明破婆,目前我們用到的就是菜單排序以及后面要用到的后臺添加自定義靜態(tài)頁面,其他的應(yīng)該沒什么了胸囱,到目前為止完整的配置文件代碼如下:)
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
# 富文本編輯器設(shè)置
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 (`<b>`, `<i>`, ...) 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': '內(nèi)容管理', 'app_label': 'blog', 'items': [
{'name': 'article'},
{'name': 'tag'},
{'name': 'category'},
]},
{'label': '附件管理', 'app_label': 'django_summernote', 'items': [
{'label': '附件列表', 'name': 'attachment'},
]},
{'label': '權(quán)限管理', 'items': [
{'name': 'auth.user', 'permissions': ['auth.user']},
{'name': 'auth.group', 'permissions': ['auth.user']},
]},
]
測試
以上步驟完成以后重啟開發(fā)服務(wù)器祷舀,查看頁面顯示結(jié)果。
全部代碼已分享至Github:https://github.com/leeyis/jbt_blog
有賬戶的不妨star一下啦~