在上一篇內容網站搭建 (第21天) 評論功能設計,已經將評論的模型使用,ajax的加載以及ckeditor評論樣式大體都介紹了一遍。其實無論是ckeditor仍是ueditor都很是的好用,在學會了如何配置ckeditor編輯框和評論框之後,我開始轉向了ueditor的學習,我的以爲ueditor在外觀上來看,要比ckeditor好一點點,做爲編輯框或者評論框都是很是的適合。在此次改寫評論框樣式,代碼層面須要修改的並很少,只須要對上篇內容的代碼進行兩處修改,一處是定義評論表單的form.py文件,須要對text字段的widget稍做修改,另外一處則是表單提交的代碼部分。此外,在瞭解這部份內容,還須要對ueditor有一個瞭解,不懂的朋友能夠先看看我以前將ueditor應用到django後臺的文章—網站搭建 (第10天) Ueditor編輯器。javascript
主要區別就是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
<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>
一樣地,在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; });
其實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