欢迎来到Felix的博客

Do the right things! And talk is cheap,show me your code!

搭建自己的博客(二十):优化博客评论功能

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 p span{
    margin-right: 10px;
}

div.blog-info-description {
    list-style-type: none;
    margin-bottom: 1em;
}

ul.blog-info-description li {
    display: inline-block;
    margin-right: 1em;
}

div.paginator {
    text-align: center;
}

div.container {
    max-width: 80%;
}

div.comment-area{
    margin-top: 2em;
}

h3.comment-area-title{
    border-bottom: 1px solid #ccc;
    padding-bottom: 0.4em;
}
blog.css
{# 引用模板 #}
{% extends 'base.html' %}

{% load staticfiles %}
{% block header_extends %}
    <link rel="stylesheet" href="{% static 'blog/blog.css' %}">
{% endblock %}


{# 标题 #}
{% block title %}
    {{ blog.title }}
{% endblock %}

{# 内容#}
{% block content %}
    <div class="container">
        <div class="row">
            <div class="col-10 offset-1">
                <ul class="blog-info-description">
                    <h3>{{ blog.title }}</h3>
                    <li>作者:{{ blog.author }}</li>
                    {# 时间过滤器让时间按照自己需要的格式过滤 #}
                    <li>发布日期:{{ blog.created_time|date:"Y-m-d H:n:s" }}</li>
                    <li>分类:
                        <a href="{% url 'blogs_with_type' blog.blog_type.pk %}">
                            {{ blog.blog_type }}
                        </a>
                    </li>
                    <li>阅读({{ blog.get_read_num }})</li>
                </ul>
                <p class="blog-content">{{ blog.content|safe }}</p>


                <p>上一篇:
                    {% if previous_blog %}
                        <a href="{% url 'blog_detail' previous_blog.pk %}">{{ previous_blog.title }}</a>
                    {% else %}
                        <span>没有了</span>
                    {% endif %}
                </p>
                <p>下一篇:
                    {% if next_blog %}
                        <a href="{% url 'blog_detail' next_blog.pk %}">{{ next_blog.title }}</a>
                    {% else %}
                        <span>没有了</span>
                    {% endif %}
                </p>
            </div>
        </div>
        <div class="row">
            <div class="col-10 offset-1">
                <div class="comment-area">
                    <h3 class="comment-area-title">提交评论</h3>
                    {% if user.is_authenticated %}
                        <form action="{% url 'update_comment' %}" method="post" style="overflow: hidden">
                            {% csrf_token %}
                            <div class="form-group">
                                <label for="form-control">{{ user.username }},欢迎评论~</label>
                                <textarea class="form-control" name="text" id="comment_text" rows="4"></textarea>
                            </div>
                            <input type="hidden" name="object_id" value="{{ blog.pk }}">
                            <input type="hidden" name="content_type" value="blog">
                            <input type="submit" value="评论" class="btn btn-primary float-right">
                        </form>
                    {% else %}
                        未登录,登录之后方可评论
                        <form action="{% url 'login' %}" method="post">
                            {% csrf_token %}
                            <span>用户名:</span>
                            <input type="text" name="username">
                            <span>密码:</span>
                            <input type="password" name="password">
                            <input type="submit" value="登录">
                        </form>
                    {% endif %}
                </div>
                <div class="-comment-area">
                    <h3 class="comment-area-title">评论列表</h3>
                    {% for comment in comments %}
                        <div>
                            {{ comment.user.username }}
                            {{ comment.comment_time|date:"Y-m-d H:n:s" }}
                            {{ comment.text }}
                        </div>
                    {% empty %}

                    {% endfor %}
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block js %}
    <script>
        $(".nav-blog").addClass("active").siblings().removeClass("active");
    </script>
{% endblock %}
blog_detail.html
from django.shortcuts import render, get_object_or_404
from django.contrib.contenttypes.models import ContentType
from django.core.paginator import Paginator
from django.conf import settings
from django.db.models import Count
from read_statistics.utils import read_statistics_once_read
from .models import Blog, BlogType
from comment.models import Comment


# 分页部分公共代码
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)))  # 获取需要显示的页码 并且剔除不符合条件的页码

    blog_dates = Blog.objects.dates('created_time', 'month', order='DESC')
    blog_dates_dict = {}
    for blog_date in blog_dates:
        blog_count = Blog.objects.filter(created_time__year=blog_date.year, created_time__month=blog_date.month).count()
        blog_dates_dict = {
            blog_date: blog_count
        }

    return {
        'blogs': page_of_blogs.object_list,
        'page_of_blogs': page_of_blogs,
        'blog_types': BlogType.objects.annotate(blog_count=Count('blog')),  # 添加查询并添加字段
        'page_range': page_range,
        'blog_dates': blog_dates_dict
    }


# 博客列表
def blog_list(requests):
    blogs_all_list = Blog.objects.all()  # 获取全部博客
    context = blog_list_common_data(requests, blogs_all_list)
    return render(requests, '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(requests, '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(requests, 'blog/blog_with_date.html', context)


# 博客详情
def blog_detail(requests, blog_pk):
    blog = get_object_or_404(Blog, pk=blog_pk)
    obj_key = read_statistics_once_read(requests, blog)

    blog_content_type = ContentType.objects.get_for_model(blog)
    comments = Comment.objects.filter(content_type=blog_content_type, object_id=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(),
        'comments': comments,  # 评论内容
    }
    response = render(requests, 'blog/blog_detail.html', context)
    response.set_cookie(obj_key, 'true')

    return response
blog下的views.py
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.auth.models import User


# Create your models here.

class Comment(models.Model):
    content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

    text = models.TextField()
    comment_time = models.DateTimeField(auto_now_add=True)
    user = models.ForeignKey(User, on_delete=models.DO_NOTHING)

    class Meta:
        ordering = ['-comment_time']
comment下的models.py
# -*- coding: utf-8 -*-
# @Time    : 18-11-4 下午5:22
# @Author  : Felix Wang

from django.urls import path
from . import views

urlpatterns = [
    path('update_comment',views.update_commit,name='update_comment')
]
comment下的urls.py
from django.shortcuts import render, reverse, redirect
from .models import Comment
from django.contrib.contenttypes.models import ContentType


def update_commit(requests):
    referer = requests.META.get('HTTP_REFERER', reverse('home'))  # 访问过来的页面
    if not requests.user.is_authenticated:  # 判断用户是否登录
        return render(requests, 'error.html', {'message': '用户未登录', 'redirect_to': referer})

    text = requests.POST.get('text', '').strip()
    if not text:  # 判断内容是否为空
        return render(requests, 'error.html', {'message': '评论内容为空', 'redirect_to': referer})

    try:
        content_type = requests.POST.get('content_type', '')
        object_id = int(requests.POST.get('object_id', ''))
        # 通过反射获取对应的模型
        model_class = ContentType.objects.get(model=content_type).model_class()
        model_obj = model_class.objects.get(pk=object_id)
    except Exception as e:
        return render(requests, 'error.html', {'message': '评论对象不存在', 'redirect_to': referer})

    # 保存评论
    comment = Comment()
    comment.user = requests.user
    comment.text = text
    comment.content_object = model_obj
    comment.save()

    return redirect(referer)
comment下的views.py
"""myblog URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from . import views

urlpatterns = [
    path('', views.home, name='home'),  # 主页路径
    path('admin/', admin.site.urls),
    path('ckeditor', include('ckeditor_uploader.urls')),  # 配置上传url
    path('blog/', include('blog.urls')),  # 博客app路径
    path('comment/', include('comment.urls')),  # 博客app路径
    path('login/', views.login, name='login'),  # 登录
]

# 设置ckeditor的上传
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
myblog下的urls.py
# -*- coding: utf-8 -*-
# @Time    : 18-11-7 下午4:12
# @Author  : Felix Wang

from django.shortcuts import render, redirect
from django.contrib.contenttypes.models import ContentType
from django.contrib import auth
from django.urls import reverse
from read_statistics.utils import get_seven_days_read_data, get_x_days_hot_data
from blog.models import Blog


def home(requests):
    blog_content_type = ContentType.objects.get_for_model(Blog)
    dates, read_nums = get_seven_days_read_data(blog_content_type)

    context = {
        'read_nums': read_nums,
        'dates': dates,
        'today_hot_data': get_x_days_hot_data(0),  # 获取今日热门
        'yesterday_hot_data': get_x_days_hot_data(1),  # 获取昨日热门
        'seven_days_hot_data': get_x_days_hot_data(7),  # 获取周热门
        'one_month_hot_data': get_x_days_hot_data(30),  # 获取月热门
    }
    return render(requests, 'home.html', context)


def login(requests):
    username = requests.POST.get('username', '')
    password = requests.POST.get('password', '')
    user = auth.authenticate(requests, username=username, password=password)
    referer = requests.META.get('HTTP_REFERER', reverse('home'))
    if user is not None:
        auth.login(requests, user)
        return redirect(referer)
    else:
        return render(requests, 'error.html', {'message': '用户名或密码错误', 'redirect_to': referer})
views.py
{% extends 'base.html' %}
{% load staticfiles %}


{% block title %}
    我的博客|错误
{% endblock %}

{% block content %}
    {{ message }} , <a href="{{ redirect_to }}">返回</a>
{% endblock %}

{% block js %}
    {# 将首页这个按钮设置激活状态 #}
    <script>
        $(".nav-home").addClass("active").siblings().removeClass("active");
    </script>
{% endblock %}
error.html

 

posted @ 2018-11-20 19:13  寂静的天空  阅读(182)  评论(0编辑  收藏  举报
个人感悟: 一个人最好的镜子就是自己,你眼中的你和别人眼中的你,不是一回事。有人夸你,别信;有人骂你,别听。一根稻草,扔街上就是垃圾;捆上白菜就是白菜价;捆上大闸蟹就是大闸蟹的价。 一个人,不狂是没有出息的,但一直狂,肯定是没有出息的。雨打残花风卷流云,剑影刀光闪过后,你满脸冷酷的站在珠峰顶端,傲视苍生无比英武,此时我问你:你怎么下去? 改变自己就是改变自己的心态,该沉的时候沉下去,该浮的时候浮上来;不争名夺利,不投机取巧,不尔虞我诈;少说、多听、多行动。人每所谓穷通寿夭为命所系,岂不知造物之报施,全视人之自取。 座佑铭:每一个不曾起舞的日子,都是对生命的辜负。