美文网首页《Django By Example》Django实战Java-Python-Django社区
Django2.0笔记(6)-开发个人博客系统(四)

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

作者: leeyis | 来源:发表于2018-03-12 11:24 被阅读82次

    开发环境

    • PyCharm 2017.3.2 (Professional Edition)

    • Python 3.6.3

    • windows 10

    • Sqlite3

    本文目标

    接上文Django2.0笔记(5)-开发个人博客系统(三),本文继续对博客系统进行优化,主要包括:

    1. 前端界面美化

    2. 文章列表分页

    3. 实现文章分类搜索和标签搜索

    无图无真相,先上效果图:

    1 2 3 4

    开发过程

    前端页面

    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里面有详细说明,目前我们用到的就是菜单排序以及后面要用到的后台添加自定义静态页面,其他的应该没什么了,到目前为止完整的配置文件代码如下:](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:https://github.com/leeyis/jbt_blog
    有账户的不妨star一下啦~

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

    相关文章

      网友评论

        本文标题:Django2.0笔记(6)-开发个人博客系统(四)

        本文链接:https://www.haomeiwen.com/subject/ztknfftx.html