我的网站搭建 (第22天) 改写评论框样式

一、前言

    在上一篇内容网站搭建 (第21天) 评论功能设计,已经将评论的模型使用,ajax的加载以及ckeditor评论样式大致都介绍了一遍。其实不管是ckeditor还是ueditor都非常的好用,在学会了如何配置ckeditor编辑框和评论框以后,我开始转向了ueditor的学习,个人觉得ueditor在外观上来看,要比ckeditor好一点点,作为编辑框或者评论框都是非常的适合。在这次改写评论框样式,代码层面需要修改的并不多,只需要对上篇内容的代码进行两处修改,一处是定义评论表单的form.py文件,需要对text字段的widget稍作修改,另一处则是表单提交的代码部分。此外,在了解这部分内容,还需要对ueditor有一个了解,不懂的朋友可以先看看我之前将ueditor应用到django后台的文章—网站搭建 (第10天) Ueditor编辑器

二、改写评论表单文件

    主要区别就是widget属性的部分,重新定义了ueditor的评论框样式,其他地方几乎没有作任何修改。

from django import forms
from django.contrib.contenttypes.models import ContentType
from django.db.models import ObjectDoesNotExist
from ckeditor.widgets import CKEditorWidget
from DjangoUeditor.widgets import UEditorWidget
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=UEditorWidget(
        attrs={"width": 'auto', "height": 180,
               "toolbars": [['fullscreen', 'source', 'undo', 'redo', 'bold', 'italic',
                             'underline', 'fontborder', 'strikethrough', 'superscript',
                             'subscript', 'removeformat', 'formatmatch', 'autotypeset',
                             'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor',
                             'insertorderedlist', 'insertunorderedlist','selectall',
                            'cleardoc', 'emotion']]}),
        error_messages={'required': '评论内容不能为空'})
    # text = forms.CharField(widget=CKEditorWidget(config_name='comment_ckeditor'),
    #                        error_messages={'required': '您尚未写任何评论内容'})

    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']
        # 找到post对象
        try:
            models_class = ContentType.objects.get(model=content_type).model_class()
            models_obj = models_class.objects.get(pk=object_id)
            self.cleaned_data['content_object'] = models_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

三、改写ajax加载评论

    1.引用ueditor的js文件
<script type="text/javascript" charset="utf-8" src="{% static 'ueditor/ueditor.config.js' %}"></script>
<script type="text/javascript" charset="utf-8" src="https://ueditor.baidu.com/ueditor/ueditor.all.min.js"> </script>
    2.改写评论表单submit代码

        同样地,在submit中,也需要对ueditor的API作一个基本了解,如getContent函数,指的是获取评论框编辑的内容,与setContent意义相反,ueditor的文档可以参考到:https://ueditor.baidu.com/doc/

// ueditor编辑框提交
$("#comment_form").submit(function(){

    // 判断是否为空
    if(id_text.getContent() == '' ){
        $("#comment_error").text('您尚未写任何评论内容');

        return false;
    }
    if(id_text.getContent().includes("让评论多一点真诚,少一点套路~") ){
        $("#comment_error").text('您尚未写任何评论内容');

        return false;
    }

    // 更新数据到textarea
    // id_text.updateElement();
    // 异步提交
    $.ajax({
        url: "{% url 'comment: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_{0}" class="comment">' +
                        '<span>{1}</span>' +
                        '<span>({2}):</span>' +
                        '<div id="comment_{0}">{3}</div>' +
                        '<div class="like" onclick="likeChange(this, \'{4}\', {0})">' +
                            '<span class="glyphicon glyphicon-thumbs-up"></span> ' +
                            '<span class="liked-num">0</span>' +
                        '</div>' +
                        '<a href="javascript:reply({0});">回复</a>' +
                        '</div>';
                    comment_html = comment_html.format(data['pk'], data['username'], timeFormat(data['comment_time']), data['text'], data['content_type']);
                    $("#comment_list").prepend(comment_html);
                }else{
                    // 插入回复
                    var reply_html = '<div class="reply">' +
                                '<span>{1}</span>' +
                                '<span>({2})</span>' +
                                '<span>回复</span>' +
                                '<span>{3}:</span>' +
                                '<div id="comment_{0}">{4}</div>' +
                                '<div class="like" onclick="likeChange(this, \'{5}\', {0})">' +
                                    '<span class="glyphicon glyphicon-thumbs-up\"></span> ' +
                                    '<span class="liked-num">0</span>' +
                                '</div>' +
                                '<a href="javascript:reply({0});">回复</a>' +
                            '</div>';
                    reply_html = reply_html.format(data['pk'], data['username'], timeFormat(data['comment_time']), data['reply_to'], data['text'], data['content_type']);
                    $("#root_" + data['root_pk']).append(reply_html);
                }

                // 清空编辑框的内容
                id_text.setContent('');
                $('#reply_content_container').hide();
                $('#reply_comment_id').val('0');
                $('#no_comment').remove();
                window.location.reload();
                $("#comment_error").text('评论成功');
            }else{
                // 显示错误信息
                $("#comment_error").text(data['message']);
            }
        },
        error: function(xhr){
            console.log(xhr);
        }
    });
    return false;
});
    3.增加评论框的placeholder效果

        其实ueditor在配置好评论框后,是没有类似input框的placeholder效果的,要实现这一功能可能需要自己实现,原理上也是使用ueditor的API来进行编写的。当用户没有点击评论框,此时进入失焦效果,此时评论框内的内容就是自己编写好的文字,只要用户点击评论框,进入focus效果,此时的内容则为空。

UE.Editor.prototype.placeholder = function (justPlainText) {
    var _editor = this;
    _editor.addListener("focus", function () {
        var localHtml = _editor.getPlainTxt();
        if ($.trim(localHtml) === $.trim(justPlainText)) {
            _editor.setContent(" ");
        }
    });
    _editor.addListener("blur", function () {
        var localHtml = _editor.getContent();
        if (!localHtml) {
            //_editor.setContent("<span>" + justPlainText + "</span>");
            _editor.setContent("<span style="+"color:#999;"+ ">" + justPlainText + "</span>");
        }
    });
    _editor.ready(function () {
        _editor.fireEvent("blur");
    });
};

$(window).load(function () {
    id_text.placeholder("让评论多一点真诚,少一点套路~");
});

    当然如果仅仅是这样子,可能还会出现bug,因为这里的placeholder并不是真正与input的placeholder效果一样,只是失焦时自动填写了确定的内容而已。所以我在submit提交代码中添加了这么一个判断语句。

if(id_text.getContent().includes("让评论多一点真诚,少一点套路~") ){
    $("#comment_error").text('您尚未写任何评论内容');
    return false;
}

原文出处:https://jzfblog.com/detail/145,文章的更新编辑以此链接为准。欢迎关注源站文章!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值