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

1、前言

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

2、改写评论表单文件

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

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

3、改写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/java

// 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效果,此时的内容则为空。python

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提交代码中添加了这么一个判断语句。ajax

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

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

相关文章
相关标签/搜索