使用自定義模板標籤實現了評論計數,獲取評論列表等功能javascript
一、變化的部分css
二、上代碼html
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; } div.django-ckeditor-widget { width: 100%; } div.comment{ border-bottom: 1px dashed #ccc; margin-bottom: 0.5em; padding-bottom: 0.5em; } div.reply{ margin-left: 2em; } div#reply-content-container{ display: block; border: 1px solid #d1d1d1; border-bottom: none; background-color: #f8f8f8; overflow: hidden; padding: 1em 1em 0.5em; } p#reply_title{ border-bottom: 1px dashed #ccc; padding-bottom: 0.5em; }
{# 引用模板 #} {% extends 'base.html' %} {% load staticfiles %} {% load comment_tags %} {% block header_extends %} <link rel="stylesheet" href="{% static 'blog/blog.css' %}"> {# 處理公式 #} <script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML' async></script> <script type="text/javascript" src="{% static "ckeditor/ckeditor-init.js" %}"></script> <script type="text/javascript" src="{% static "ckeditor/ckeditor/ckeditor.js" %}"></script> {% 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:i:s" }}</li> <li>分類: <a href="{% url 'blogs_with_type' blog.blog_type.pk %}"> {{ blog.blog_type }} </a> </li> <li>閱讀({{ blog.get_read_num }})</li> <li>評論({% get_comment_count blog %})</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 id="comment-form" action="{% url 'update_comment' %}" method="post" style="overflow: hidden"> {% csrf_token %} <label for="form-control">{{ user.username }},歡迎評論~</label> <div id="reply-content-container" style="display: none;"> <p id="reply_title">回覆:</p> <div id="reply-content"> </div> </div> {% get_comment_form blog as comment_form %} {% for field in comment_form %} {{ field }} {% endfor %} <span id="comment-error" class="text-danger float-left"></span> <input type="submit" value="評論" class="btn btn-primary float-right"> </form> {% else %} 您還沒有登陸,登陸以後方可評論 {# 提交登陸的時候帶上從哪裏訪問的路徑 #} <a class="btn btn-primary" href="{% url 'login' %}?from={{ request.get_full_path }}">登陸</a> <span> or </span> <a class="btn-danger btn" href="{% url 'register' %}?from={{ request.get_full_path }}">註冊</a> {% endif %} </div> <div class="-comment-area"> <h3 class="comment-area-title">評論列表</h3> <div id="comment-list"> {% get_comment_list blog as comments %} {% for comment in comments %} <div id="root-{{ comment.pk }}" class="comment"> <span>{{ comment.user.username }}</span> <span>{{ comment.comment_time|date:"Y-m-d H:i:s" }}</span> <div id="comment-{{ comment.pk }}">{{ comment.text|safe }}</div> <a href="javascript:reply({{ comment.pk }})">回覆</a> {% for reply in comment.root_comment.all %} <div class="reply"> <span>{{ reply.user.username }}</span> <span>{{ reply.comment_time|date:"Y-m-d H:i:s" }}</span> <span>回覆:</span><span>{{ reply.reply_to.username }}</span> <div id="comment-{{ reply.pk }}">{{ reply.text|safe }}</div> <a href="javascript:reply({{ reply.pk }})">回覆</a> </div> {% endfor %} </div> {% empty %} <span id="no-comment">暫無評論</span> {% endfor %} </div> </div> </div> </div> </div> {% endblock %} {% block js %} <script> // 處理回覆 function reply(reply_comment_id) { $('#reply_comment_id').val(reply_comment_id); let html = $('#comment-' + reply_comment_id).html(); $('#reply-content').html(html); $('#reply-content-container').show(); // 顯示內容 // 滾動富文本編輯器 $('html').animate({scrollTop: $('#comment-form').offset().top - 60}, 300, function () { // 動畫執行完畢後執行的方法 // 讓富文本編輯器得到焦點 CKEDITOR.instances['id_text'].focus(); }); } function numFormat(num) { return ('00'+num).substr(-2); } function timeFormat(timestamp) { let datetime =new Date(timestamp * 1000); let year = datetime.getFullYear(); let month = numFormat(datetime.getMonth() + 1); let day = numFormat(datetime.getDate()); let hour = numFormat(datetime.getHours()); let minute = numFormat(datetime.getMinutes()); let second = numFormat(datetime.getSeconds()); return `${year}-${month}-${day} ${hour}:${minute}:${second}` } // 提交評論 $('#comment-form').submit(function () { // 獲取錯誤框 let comment_error = $('#comment-error'); comment_error.text(''); // 更新數據到textarea CKEDITOR.instances['id_text'].updateElement(); let comment_text = CKEDITOR.instances['id_text'].document.getBody().getText().trim(); // 判斷是否爲空 if (!(CKEDITOR.instances['id_text'].document.getBody().find('img')['$'].length !== 0 || comment_text !== '')) { // 顯示錯誤信息 comment_error.text('評論內容不能爲空'); return false; } //異步提交 $.ajax({ url: "{% url 'update_comment' %}", type: 'POST', data: $(this).serialize(),// 序列化表單值 cache: false, // 關閉緩存 success: function (data) { let reply_comment = $('#reply_comment_id'); if (data['status'] === 'SUCCESS') { console.log(data); // 插入數據 // es6寫法 if (reply_comment.val() === '0') { // 插入評論 let comment_html = `<div id="root-${data["pk"]}" class="comment"> <span>${data["username"]}</span> <span>${timeFormat(data["comment_time"])}</span> <div id="comment-${data["pk"]}">${data["text"]}</div> <a href="javascript:reply(${data["pk"]})">回覆</a> </div>`; $('#comment-list').prepend(comment_html); } else { // 插入回覆 let reply_html = `<div class="reply"> <span>${data["username"]}</span> <span>${timeFormat(data["comment_time"])}</span> <span>回覆:</span><span>${data["reply_to"]}</span> <div id="comment-${data["pk"]}">${data["text"]}</div> <a href="javascript:reply(${data["pk"]})">回覆</a> </div>`; $('#root-' + data['root_pk']).append(reply_html); } // 清空編輯框的內容 CKEDITOR.instances['id_text'].setData(''); $('#reply-content-container').hide(); // 回覆完隱藏掉要回復的內容 reply_comment.val('0'); // 將回復標誌重置0 $('#no-comment').remove(); // 若是有沒回復標誌,清除掉5 comment_error.text('評論成功'); } else { // 顯示錯誤信息 comment_error.text(data['message']) } }, error: function (xhr) { console.log(xhr); } }); return false; }); </script> <script> $(".nav-blog").addClass("active").siblings().removeClass("active"); </script> {% endblock %}
{% extends 'base.html' %} {% load staticfiles %} {% load comment_tags %} {# 標題 #} {% block title %} felix Blog {% endblock %} {% block header_extends %} <link rel="stylesheet" href="{% static 'blog/blog.css' %}"> <link rel="stylesheet" href="{% static 'fontawesome-free-5.5.0-web/css/all.min.css' %}"> {% endblock %} {# 內容#} {% block content %} <div class="container"> <div class="row"> <div class="col-md-8"> <div class="card" style=""> <div class="card-header"><h5 class="card-title">{% block blog_type_title %}博客列表{% endblock %}</h5> </div> <div class="card-body"> {% for blog in blogs %} <div class="blog"> <h3><a href="{% url 'blog_detail' blog.pk %}">{{ blog.title }}</a></h3> <div class="blog-info"> <p> {# 添加圖標 #} <span> <i class="fas fa-tag"></i> <a href="{% url 'blogs_with_type' blog.blog_type.pk %}"> {{ blog.blog_type }} </a> </span> <span> <i class="far fa-clock "></i> {{ blog.created_time|date:"Y-m-d" }} </span> <span>閱讀({{ blog.get_read_num }})</span> <span>評論({% get_comment_count blog %})</span> <p> </div> <p>{{ blog.content|safe|truncatechars:30 }}</p> </div> {% empty %} <div class="blog"> <h3>--暫無博客,敬請期待--</h3> </div> {% endfor %} </div> </div> {# 分頁 #} <div class="paginator"> <ul class="pagination justify-content-center"> {# 首頁 #} <li class="page-item"><a class="page-link" href="?page=1">首頁</a></li> {# 上一頁 #} {% if page_of_blogs.has_previous %} <li class="page-item"><a class="page-link" href="?page={{ page_of_blogs.previous_page_number }}">上一頁</a> </li> {% else %} <li class="page-item disabled"><span class="page-link">上一頁</span></li> {% endif %} {# 所有頁碼 #} {% for page_num in page_range %} {# 添加當前頁高亮顯示 #} {% if page_num == page_of_blogs.number %} <li class="page-item active"><span class="page-link">{{ page_num }}</span></li> {% else %} <li class="page-item"><a class="page-link" href="?page={{ page_num }}">{{ page_num }}</a></li> {% endif %} {% endfor %} {# 下一頁 #} {% if page_of_blogs.has_next %} <li class="page-item"><a class="page-link" href="?page={{ page_of_blogs.next_page_number }}">下一頁</a></li> {% else %} <li class="page-item disabled"><span class="page-link">下一頁</span></li> {% endif %} {# 尾頁 #} <li class="page-item"><a class="page-link" href="?page={{ page_of_blogs.paginator.num_pages }}">尾頁</a></li> </ul> <p> 一共有 {{ page_of_blogs.paginator.count }}篇博客,當前{{ page_of_blogs.number }}頁,共{{ page_of_blogs.paginator.num_pages }}頁 </p> </div> </div> <div class="col-md-4"> <div class="card"> <div class="card-header"><h5 class="card-title">博客分類</h5></div> <div class="card-body"> <ul class="blog-types"> {% for blog_type in blog_types %} <li> <a href="{% url 'blogs_with_type' blog_type.pk %}">{{ blog_type.type_name }}({{ blog_type.blog_count }})</a> </li> {% empty %} <li>暫無分類</li> {% endfor %} </ul> </div> </div> <div class="card"> <div class="card-header"><h5 class="card-title">日期歸檔</h5></div> <div class="card-body"> <ul class="blog-dates"> {% for blog_date,blog_count in blog_dates.items %} <li> <a href="{% url 'blogs_with_date' blog_date.year blog_date.month %}"> {{ blog_date|date:'Y年m月' }}({{ blog_count }}) </a> </li> {% empty %} <li>暫無分類</li> {% endfor %} </ul> </div> </div> </div> </div> </div> {% endblock %} {% block js %} <script> $(".nav-blog").addClass("active").siblings().removeClass("active"); </script> {% endblock %}
from django.db import models from django.contrib.auth.models import User from django.contrib.contenttypes.fields import GenericRelation from ckeditor_uploader.fields import RichTextUploadingField from django.contrib.contenttypes.models import ContentType from read_statistics.models import ReadNumExpandMethod, ReadDetail # Create your models here. # 博客分類 class BlogType(models.Model): type_name = models.CharField(max_length=15) # 博客分類名稱 def __str__(self): # 顯示標籤名 return self.type_name # 博客 class Blog(models.Model, ReadNumExpandMethod): title = models.CharField(max_length=50) # 博客標題 blog_type = models.ForeignKey(BlogType, on_delete=models.CASCADE) # 博客分類 content = RichTextUploadingField() # 博客內容,使用富文本編輯 author = models.ForeignKey(User, on_delete=models.CASCADE) # 博客做者 read_details = GenericRelation(ReadDetail) # 關聯到閱讀表 created_time = models.DateTimeField(auto_now_add=True) # 博客建立時間 last_updated_time = models.DateTimeField(auto_now=True) # 博客更新事件 def __str__(self): # 顯示標題名 return "<Blog:{}>".format(self.title) class Meta: ordering = ['-created_time'] # 定義排序規則,按照建立時間倒序
from django.shortcuts import render, get_object_or_404 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 # 分頁部分公共代碼 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) 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(), } response = render(requests, 'blog/blog_detail.html', context) response.set_cookie(obj_key, 'true') return response
# -*- coding: utf-8 -*- # @Time : 18-11-22 下午7:48 # @Author : Felix Wang from django import template from django.contrib.contenttypes.models import ContentType from ..models import Comment from ..forms import CommentForm # 註冊自定義模板標籤 register = template.Library() # 獲取評論計數 @register.simple_tag def get_comment_count(obj): content_type = ContentType.objects.get_for_model(obj) return Comment.objects.filter(content_type=content_type, object_id=obj.pk).count() # 獲取評論表單 @register.simple_tag def get_comment_form(obj): content_type = ContentType.objects.get_for_model(obj) return CommentForm( initial={'content_type': content_type.model, 'object_id': obj.pk, 'reply_comment_id': 0}) # 獲取評論列表 @register.simple_tag def get_comment_list(obj): content_type = ContentType.objects.get_for_model(obj) comments = Comment.objects.filter(content_type=content_type, object_id=obj.pk, parent=None) return comments.order_by('-comment_time') # 評論內容
from django.contrib import admin from .models import Comment # Register your models here. @admin.register(Comment) class CommentAdmin(admin.ModelAdmin): list_display = ('id', 'content_object', 'text', 'comment_time', 'user', 'root', 'parent')
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.CASCADE) 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, related_name='comments', on_delete=models.CASCADE) root = models.ForeignKey('self', related_name='root_comment', null=True, on_delete=models.CASCADE) # 兩個外鍵關聯同一個表時,經過related_name來解決衝突 parent = models.ForeignKey('self', related_name='parent_comment', null=True, on_delete=models.CASCADE) reply_to = models.ForeignKey(User, related_name='replies', on_delete=models.CASCADE, null=True) def __str__(self): return self.text class Meta: ordering = ['comment_time']
from django.http import JsonResponse from .models import Comment from .forms import CommentForm def update_commit(requests): comment_form = CommentForm(requests.POST, user=requests.user) if comment_form.is_valid(): comment = Comment() comment.user = comment_form.cleaned_data['user'] comment.text = comment_form.cleaned_data['text'] comment.content_object = comment_form.cleaned_data['content_object'] parent = comment_form.cleaned_data['parent'] if parent is not None: comment.root = parent.root if parent.root is not None else parent comment.parent = parent comment.reply_to = parent.user comment.save() # 返回數據 data = { 'status': 'SUCCESS', 'username': comment.user.username, 'comment_time': comment.comment_time.timestamp(), # 返回時間戳 'text': comment.text.strip(), 'reply_to': comment.reply_to.username if parent is not None else '', 'pk': comment.pk, 'root_pk': comment.root.pk if comment.root is not None else '', } else: data = { 'status': 'ERROR', 'message': list(comment_form.errors.values())[0][0], } return JsonResponse(data)