我们在后台admin已经用过富文本编辑来编辑我们的博客,这次我们用它提供的这个Widget类,给我们去渲染出一个富文本编辑器在前端的末班页面。
这个Widget可以去给DjangoForm表单去使用。
1、django-ckeditor富文本编辑表单
每个字段类型都有一个适当的默认Widget类
django-ckeditor提供widget
from ckeditor.widgets import CKEditorWidget
首先在评论app中创建forms.py文件,写一个评论表单取代原来前端的Html,和评论的views中的处理数据逻辑。
from django import forms from django.contrib.contenttypes.models import ContentType from django.db.models import ObjectDoesNotExist class CommentForm(forms.Form): content_type = forms.CharField(widget=forms.HiddenInput) object_id = forms.IntegerField(widget=forms.HiddenInput) text = forms.CharField(widget=forms.Textarea) 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
前端
<form action="{% url ‘update_comment‘ %}" method="POST" style="overflow: hidden"> <label>{{ user.username }},欢迎评论~</label> {% csrf_token %} {{ comment_form }} <input type="submit" value="评论" class="btn btn-primary" style="float: right"> </form>
博客views
context[‘comment_form‘] = CommentForm(initial={‘content_type‘:blog_content_type.model, ‘object_id‘:blog_pk})
评论views
from django.shortcuts import render, redirect from django.contrib.contenttypes.models import ContentType from django.urls import reverse 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) 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‘] comment.save() return redirect(referer) else: return render(request, ‘error.html‘, {‘message‘: comment_form.errors, ‘redirect_to‘: referer})
评论views
from django.urls import path from . import views urlpatterns = [ path(‘update_comment‘,views.update_comment,name=‘update_comment‘), ]
把前端评论框改成富文本编辑使用django-ckeditor
在评论forms中导入
from ckeditor.widgets import CKEditorWidget
把text修改
text = forms.CharField(widget=CKEditorWidget(config_name=‘comment_ckeditor‘))
之后给博客页面加入js链接
<script type="text/javascript" src="{% static "ckeditor/ckeditor-init.js" %}"></script>
<script type="text/javascript" src="{% static "ckeditor/ckeditor/ckeditor.js" %}"></script>
如果要对富文本编辑框进行修改,可以参考github里的django-ckeditor,在settins中
CKEDITOR_CONFIGS = { ‘default‘:{}, ‘comment_ckeditor‘: { ‘toolbar‘: ‘custom‘, ‘toolbar_custom‘: [ [‘Bold‘, ‘Italic‘, ‘Underline‘, ‘Strike‘, ‘Subscript‘, ‘Superscript‘], ["TextColor", "BGColor", ‘RemoveFormat‘], [‘NumberedList‘, ‘BulletedList‘], [‘Link‘, ‘Unlink‘], ["Smiley", "SpecialChar", ‘Blockquote‘], ], ‘width‘: ‘auto‘, ‘height‘: ‘180‘, ‘tabSpaces‘: 4, ‘removePlugins‘: ‘elementspath‘, ‘resize_enabled‘: False, } }
此时提交信息后页面会进行刷新,需要使用ajax。
2.ajax提交
正常提交会刷新页面,可以ajax提交数据
ajax提交是一种不刷新页面的异步提交方式
在博客页面为评论表单、评论错误、评论列表表单分别设置id值,方便查找。comment_form,comment_error,comment_list
之后写jquery ajax进行异步提交数据。
{% 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‘){ //插入数据 var comment_html = ‘<div>‘ + data[‘username‘] + ‘ (‘ + data[‘comment_time‘] + ‘): ‘ + data[‘text‘] + ‘</div>‘; $(‘#comment_list‘).prepend(comment_html); //清空编辑框的内容 CKEDITOR.instances[‘id_text‘].setData(‘‘) }else { //显示错误信息 $(‘#comment_error‘).text(data[‘message‘]); } }, error: function (xhr) { console.log(xhr); } }); return false; }); </script> {% endblock %}
在views处理方法中,处理数据后返回信息
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‘] 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 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})