(六)Django 在线平台(用户评论功能)

配置前端页面course-comments.html页面

配置前端页面url和显示项前面几乎一样


编写view视图函数

class CommentsView(View):
    """
        将后台数据传递给前端课程评论页面
    """
    def get(self, request, course_id):
        course = Course.objects.get(id=int(course_id))
        all_resourse = CourseResource.objects.filter(course=course)
        all_comments = CourseComments.objects.all()
        return render(request, 'course-comment.html', {
            'course': course,
            'course_resources': all_resourse,
            'all_comments': all_comments
        })


class AddCommentsView(View):
    """
        用户课程评论
    """
    def post(self, request):
        if not request.user.is_authenticated():
            # 判断用户登录状态
            return HttpResponse('{"status":"fail", "msg":"用户未登录"}',
                                content_type='application/json')
        course_id = request.POST.get('course_id', '0')
        comments = request.POST.get('comments', '')
        if course_id > 0 and comments:
            course_comments = CourseComments()
            course = Course.objects.get(id=int(course_id))
            course_comments.course = course
            course_comments.comments = comments
            course_comments.user = request.user
            course_comments.save()
            return HttpResponse('{"status":"success", "msg":"添加成功"}',
                                content_type='application/json')
        else:
            return HttpResponse('{"status":"fail", "msg":"添加失败"}',
                                content_type='application/json')

配置urls

# !/usr/bin/env python 
# -*- coding:utf-8 -*-
__author__ = '_X.xx_'
__date__ = '2018/6/9 19:00'

from django.conf.urls import url
from .views import CourseListView, CourseDetailView, CourseInfoView, \
    CommentsView, AddCommentsView

urlpatterns = [
    # 课程列表
    url(r'^list/$', CourseListView.as_view(), name="course_list"),
    # 课程详情页
    url(r'^detail/(?P<course_id>\d+)/$', CourseDetailView.as_view(),
        name="course_detail"),
    url(r'^info/(?P<course_id>\d+)/$', CourseInfoView.as_view(),
        name="course_info"),
    # 课程评论
    url(r'^comment/(?P<course_id>\d+)/$', CommentsView.as_view(),
        name="course_comments"),
    # 添加课程评论
    url(r'^add_comment/$', AddCommentsView.as_view(),
        name="add_comment"),

]

评论功能是Ajax请求 只有评论页有的单独功能 在评论页面编写js

{% block custom_js %}
<script type="text/javascript">
    //添加评论
    $('#js-pl-submit').on('click', function(){
        var comments = $("#js-pl-textarea").val()
        if(comments == ""){
            alert("评论不能为空")
            return
        }
        $.ajax({
            cache: false,
            type: "POST",
            url:"{% url 'course:add_comment' %}",
            data:{'course_id':{{ course.id }}, 'comments':comments},
            async: true,
            beforeSend:function(xhr, settings){
                xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
            },
            success: function(data) {
                if(data.status == 'fail'){
                    if(data.msg == '用户未登录'){
                        window.location.href="/login/";
                    }else{
                        alert(data.msg)
                    }

                }else if(data.status == 'success'){
                    window.location.reload();//刷新当前页面.
                }
            },
        });
    });

</script>
{% endblock %}

前端页面获取后台评论数据

<ul class="mod-post" id="comment-list">
    {% for user_comment in all_comments %}
            <li class="post-row">
        <div class="media">
            <span target="_blank"><img src='{{ MEDIA_URL }}{{ user_comment.user.image }}' width='40' height='40' /></span>
        </div>
        <div class="bd">
            <div class="tit">
                <span target="_blank">{{ user_comment.user.username }}</span>
            </div>
            <p class="cnt">{{ user_comment.comments }}</p>
            <div class="footer clearfix">
                <span title="创建时间" class="l timeago">时间:{{ user_comment.add_time }}</span>
            </div>
        </div>
    </li>
    {% endfor %}
(六)Django 在线平台(用户评论功能)