首页 > 其他 > 详细

回复功能设计和树结构

时间:2020-11-02 20:57:37      阅读:25      评论:0      收藏:0      [点我收藏+]

1、如何设计回复功能

评论被回复

回复可被回复

如果设计指向上一级回复模型需要设计无限多个,不合理。

回复也是一种评论的行为,本质是评论。

所以让回复在评论里面实现。

更改评论模型

from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.contrib.auth.models import User

class Comment(models.Model):
    # 将您的模型ForeignKey 设为ContentType 通过ContentType找到具体的模型
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()  # 记录对应模型的主键值 该字段可以存储您将要关联的模型中的主键值
    # 给您的模型一个 GenericForeignKey,并为其传递上述两个字段的名称。如果将这些字段分别命名
    # 为“ content_type”和“ object_id”,则可以忽略这些-这些是默认字段名称 GenericForeignKey。
    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)
    #记录上一级的相关信息 指向自己 顶级是可以为空
    parent = models.ForeignKey(self, related_name=parent_comment, null=True, on_delete=models.CASCADE)
    #回复谁
    reply_to = models.ForeignKey(User, related_name=replies, null=True, on_delete=models.CASCADE)

    def __str__(self):
        return self.text

    class Meta:
        ordering = [comment_time]

博客页面获取评论时可以做筛选,只显示顶级评论,前端页面再在顶级评论下遍历出回复

comments = Comment.objects.filter(content_type=blog_content_type,object_id=blog.pk,parent=None)
context[‘comments‘] = comments.order_by(‘-comment_time‘)
context[‘comment_form‘] = CommentForm(initial={‘content_type‘:blog_content_type.model, ‘object_id‘:blog_pk, ‘reply_comment_id‘:0})

前端
<h3 class="comment-area-title">评论列表</h3>
                    <div id="comment_list">
                        {% 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>

回复可以在在评论的富文本编辑器中实现

from django import forms
from django.contrib.contenttypes.models import ContentType
from django.db.models import ObjectDoesNotExist
from ckeditor.widgets import CKEditorWidget
from .models import Comment


class CommentForm(forms.Form):
    content_type = forms.CharField(widget=forms.HiddenInput)
    object_id = forms.IntegerField(widget=forms.HiddenInput)
    text = forms.CharField(widget=CKEditorWidget(config_name=comment_ckeditor),error_messages={required:评论内容不能为空})
    #回复的对应评论的主键值,id值可以通过前端页面获取
    reply_comment_id = forms.IntegerField(widget=forms.HiddenInput(attrs={id:reply_comment_id}))

    def __init__(self, *args, **kwargs):
        if user in kwargs:
            self.user = kwargs.pop(user)
        super(CommentForm, self).__init__(*args, **kwargs)

    def clean(self):
        #判断用户是否登录
        if self.user.is_authenticated:
            self.cleaned_data[user] = self.user
        else:
            raise forms.ValidationError(用户尚未登录)
        #评论对象验证
        content_type = self.cleaned_data[content_type]
        object_id = self.cleaned_data[object_id]
        try:
            model_class = ContentType.objects.get(model=content_type).model_class()
            model_obj = model_class.objects.get(pk=object_id)
            self.cleaned_data[content_object] =model_obj
        except ObjectDoesNotExist:
            raise forms.ValidationError(评论对象不存在)
        return self.cleaned_data

    def clean_reply_comment_id(self):
        reply_comment_id = self.cleaned_data[reply_comment_id]
        if reply_comment_id < 0:
            raise forms.ValidationError(回复出错)
        elif reply_comment_id == 0:
            self.cleaned_data[parent] = None
        elif Comment.objects.filter(pk=reply_comment_id).exists():
            self.cleaned_data[parent] = Comment.objects.get(pk=reply_comment_id)
        else:
            raise forms.ValidationError(回复出错)
        return reply_comment_id

之后写前端页面的js代码和回复的处理逻辑

{% extends base.html %}

{% block title %}
    {{ blog.title }}
{% endblock %}

{% block nav_blog_active %}active{% endblock %}

{% load staticfiles %}
{% block header_extends %}
    <link rel="stylesheet" href="{% static ‘blog/blog.css‘ %}">
    <script type="text/javascript" src="{% static "ckeditor/ckeditor-init.js" %}"></script>
    <script type="text/javascript" src="{% static "ckeditor/ckeditor/ckeditor.js" %}"></script>
{% endblock %}

{% block content %}
    <div class="container">
        <div class="row">
            <div class="col-xs-10 col-xs-offset-1">
                <h3>{{ blog.title }}</h3>
                <ul class="blog-info-description">
                    <li>作者:{{ blog.author }}</li>
                    <li>分类:<a href="{% url ‘blogs_with_type‘ blog.blog_type.pk %}">{{ blog.blog_type }}</a></li>
                    <li>发表日期:{{ blog.created_time|date:"Y-m-d H:i:s" }}</li>
                    <li>阅读({{ blog.get_read_num }})</li>
                </ul>
                <div class="blog-content">{{ blog.content|safe }}</div>
                <div class="blog-more">
                    <p>上一篇:
                        {% if previous_blog %}
                            <a href="{% url ‘blog_detail‘ previous_blog.pk %}">{{ previous_blog.title }}</a>
                        {% else %}
                            没有了
                        {% endif %}
                    </p>
                    <p>下一篇:
                        {% if next_blog %}
                            <a href="{% url ‘blog_detail‘ next_blog.pk %}">{{ next_blog.title }}</a>
                        {% else %}
                            没有了
                        {% endif %}
                    </p>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-10 col-xs-offset-1">
                <div class="comment-area">
                    <h3 class="comment-area-title">提交评论</h3>
                    {% if request.user.is_authenticated %}
                        <form id="comment_form" action="{% url ‘update_comment‘ %}" method="POST" style="overflow: hidden">
                            <label>{{ user.username }},欢迎评论~</label>
                            <div id="reply_content_container" style="display: none;">
                                <p>回复:</p>
                                <div id="reply_content">

                                </div>
                            </div>
                            {% csrf_token %}
                            {% for field in comment_form %}
                                {{ field }}
                            {% endfor %}
                            <span id="comment_error" class="text-danger pull-left"></span>
                            <input type="submit" value="评论" class="btn btn-primary pull-right">
                        </form>
                    {% else %}
                        您尚未登录,登录之后方可评论
                        <a class="btn btn-primary" href="{% url ‘login‘ %}?from={{ request.get_full_path }}">登录</a>
                        <span>or</span>
                        <a class="btn btn-danger" 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">
                        {% 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 script_extends %}
    <script type="text/javascript">
        $(#comment_form).submit(function () {
            //判断是否为空
            $(#comment_error).text(‘‘);
            if(CKEDITOR.instances["id_text"].document.getBody().getText().trim()==‘‘){
                $(#comment_error).text(评论内容不能为空);
                return false
            }
            //更新数据到textarea里边
            CKEDITOR.instances["id_text"].updateElement();
            //异步提交,标签选择器选中form表单,当表单提交的时候会触发submit()方法,触发事件的时候回调一个function
            //这个function作为一个参数写到这里 return false 会阻止它点完按钮直接提交这个操作,这里我们需要一个异步提交
            $.ajax({
                url: "{% url ‘update_comment‘ %}",
                type: POST,
                data: $(this).serialize(),
                cache: false,
                success: function (data) {
                    console.log(data);
                    //判断是否处理成功
                    if(data[status]==SUCCESS){
                        //插入数据


                        if($(#reply_comment_id).val()==0){
                            //插入评论
                            var comment_html = <div id="root_ + data[pk] + " class="comment"><span> + data[username] + </span><span> ( + 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 {
                            //插入回复
                            var reply_html =<div class="reply"><span> + data[username] + </span><span> ( + 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_id).val(0);
                        $(#no_comment).remove();
                    }else {
                        //显示错误信息
                        $(#comment_error).text(data[message]);
                    }

                },
                error: function (xhr) {
                    console.log(xhr);
                }
            });
            return false;
        });
        function reply(reply_comment_id) {
            //设置值
            $(#reply_comment_id).val(reply_comment_id);
            var 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();

            });
        }
    </script>
{% endblock %}

回复处理逻辑

from django.shortcuts import render, redirect
from django.contrib.contenttypes.models import ContentType
from django.urls import reverse
from django.http import JsonResponse
from .models import Comment
from .forms import CommentForm

def update_comment(request):
    ‘‘‘referer = request.META.get(‘HTTP_REFERER‘, reverse(‘home‘))
    #数据检查
    user = request.user
    if not user.is_authenticated:
        return render(request,‘error.html‘,{‘message‘:‘用户未登录‘,‘redirect_to‘:referer })
    text = request.POST.get(‘text‘,‘‘).strip()
    if text == ‘‘:
        return render(request,‘error.html‘,{‘message‘:‘评论内容为空‘,‘redirect_to‘:referer })
    try:
        content_type = request.POST.get(‘content_type‘,‘‘)
        object_id = int(request.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(request, ‘error.html‘, {‘message‘: ‘评论对象不存在‘,‘redirect_to‘:referer })

    #检查通过,保存数据
    comment = Comment()
    comment.user = user
    comment.text = text
    comment.content_object = model_obj
    comment.save()
    return redirect(referer)‘‘‘
    referer = request.META.get(HTTP_REFERER, reverse(home))
    comment_form = CommentForm(request.POST, user=request.user)
    data = {}
    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 not parent is None:
            comment.root = parent.root if not parent.root is None else parent
            comment.parent = parent
            comment.reply_to = parent.user
        comment.save()

        #返回数据
        data[status] = SUCCESS
        data[username] = comment.user.username
        data[comment_time] = comment.comment_time.strftime(%Y-%m-%d %H:%M:%S)
        data[text] = comment.text
        if not parent is None:
            data[reply_to] = comment.reply_to.username
        else:
            data[reply_to] = ‘‘
        data[pk] = comment.pk
        data[root_pk] = comment.root.pk if not comment.root is None else ‘‘
    else:
        data[status] = ERROR
        data[message] = list(comment_form.errors.values())[0][0]
    return JsonResponse(data)
        # return render(request, ‘error.html‘, {‘message‘: comment_form.errors, ‘redirect_to‘: referer})

 

回复功能设计和树结构

原文:https://www.cnblogs.com/lag1/p/13915737.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!