Django2.0笔记(6)-开发个人博客系统(四)

开发环境

  • 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

<!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 %}&nbsp;
                    </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>
                        &nbsp;
                        <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>
                        &nbsp;
                        <a href="https://github.com/leeyis/" style="text-decoration: none" title="Github">
                            <i class="fa fa-github" style="font-size: 34px" aria-hidden="true"></i>
                        </a>
                        &nbsp;
                    </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> 标签把 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 %}
    <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>&nbsp;{{ post.pub_time |date:'Y-m-d'}}&nbsp;&nbsp;
                        <i class="fa fa-eye" aria-hidden="true"></i>&nbsp;{{ post.views }}次浏览
                    </p>
                </header>

                <div class="post-description">
                    <p>
                        {#striptags用于过滤正文中所有的HTML标签#}
                        {#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>&nbsp;&nbsp;上一页
                </a>
            {% endif %}
            {% if post_list.has_next %}
                <a class="footer" href="?page={{ post_list.next_page_number }}" style="text-decoration: none; float: right;">
                    下一页&nbsp;&nbsp;<i class="fa fa-angle-right"></i>
                </a>
            {% endif %}
        </div>
    {% endif %}
{% endblock %}

3.文章详情页增加Font Awesome 图标、分类和标签搜索,页面代码如下:

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>&nbsp; {{ post.pub_time|date:'Y-m-d H:m:s'}}&nbsp;&nbsp;
                        <i class="fa fa-list-alt"></i>&nbsp;<a class="post-category post-category-pure" href="{% url 'category_menu' id=post.category_id %}" style="text-decoration: none">{{ post.category }}</a>&nbsp;&nbsp;
                        <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 %}&nbsp;&nbsp;
                        <i class="fa fa-eye" aria-hidden="true"></i>&nbsp;{{ post.views }}次浏览
                    </p>
            </header>

                <div class="post-description">
                    <p>
                        {{ post.content |safe}}
                    </p>
                </div>
        </section>
</div><!-- /.blog-post -->
{% endblock %}

4.分类搜索结果页、标签搜索结果页和主页文章列表页结构类似,区别在于文章列表页显示的是没有加筛选条件的结果,分类搜索结果页是显示特定分类的文章列表,标签搜索结果页是显示特定标签的文章列表,分类搜索结果页代码如下:

category.html

{% extends "base.html" %}
{% load static %}
{% block content %}
  <h1 class="content-subhead">分类:&nbsp;<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>&nbsp;{{ post.pub_time |date:'Y-m-d'}}&nbsp;&nbsp;
                        <i class="fa fa-eye" aria-hidden="true"></i>&nbsp;{{ post.views }}次浏览
                    </p>
                </header>

                <div class="post-description">
                    <p>
                        {#striptags用于过滤正文中所有的HTML标签#}
                        {#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>&nbsp;&nbsp;上一页
                </a>
            {% endif %}
            {% if post_list.has_next %}
                <a class="footer" href="?page={{ post_list.next_page_number }}" style="text-decoration: none; float: right;">
                    下一页&nbsp;&nbsp;<i class="fa fa-angle-right"></i>
                </a>
            {% endif %}
        </div>
  {% endif %}
{% endblock %}

标签搜索结果页页面代码如下:

tag.html

{% extends "base.html" %}
{% load static %}
{% block content %}
  <h1 class="content-subhead">标签:&nbsp;<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>&nbsp;{{ post.pub_time |date:'Y-m-d'}}&nbsp;&nbsp;
                        <i class="fa fa-eye" aria-hidden="true"></i>&nbsp;{{ post.views }}次浏览
                    </p>
                </header>

                <div class="post-description">
                    <p>
                        {#striptags用于过滤正文中所有的HTML标签#}
                        {#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>&nbsp;&nbsp;上一页
                </a>
            {% endif %}
            {% if post_list.has_next %}
                <a class="footer" href="?page={{ post_list.next_page_number }}" style="text-decoration: none; float: right;">
                    下一页&nbsp;&nbsp;<i class="fa fa-angle-right"></i>
                </a>
            {% endif %}
        </div>
  {% 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/<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'),  # 标签搜索
    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里面有详细说明,目前我们用到的就是菜单排序以及后面要用到的后台添加自定义静态页面,其他的应该没什么了,到目前为止完整的配置文件代码如下:

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 (`<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': '内容管理', '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 有账户的不妨star一下啦~


更多原创文章,尽在金笔头博客

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Django是一个使用Python编写的Web应用程序框架,它提供了许多强大的工具和功能来帮助开发人员快速构建高效的Web应用程序。 要玩转Django 2.0代码,首先需要安装Django 2.0,并且熟悉其基本的目录结构和文件组织方式。在创建一个新的Django项目时,可以使用命令行工具来生成基本的项目结构,然后在其中创建应用程序并定义模型、视图和模板。 在使用Django 2.0开发Web应用程序时,需要熟悉Django的MTV(模型-模板-视图)架构,这是Django应用程序的核心概念。模型用于定义数据结构和处理数据库操作,视图负责处理用户请求并返回响应,模板则用于生成最终的用户界面。 此外,了解如何使用Django 2.0的路由系统来处理URL映射和视图函数的调度也非常重要。可以使用Django的路由配置来定义URL模式,并将它们映射到相应的视图函数上。 另外,了解Django 2.0的表单处理、认证和权限管理功能也是必不可少的。Django提供了丰富的表单组件和验证工具,可以帮助开发人员快速构建复杂的表单。而用户认证和权限管理方面,Django提供了强大的认证和授权系统,可以帮助开发人员轻松实现用户注册、登录和权限控制。 总之,要玩转Django 2.0代码,需要深入了解Django的核心概念和功能,并且通过实际的项目实践来提升自己的编码技巧和经验。希望以上回答能帮助你更好的学习和应用Django 2.0

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值