美文网首页
2020-05-19--Django项目17--课程章节的评论,

2020-05-19--Django项目17--课程章节的评论,

作者: program_white | 来源:发表于2020-05-20 15:50 被阅读0次

课程章节的评论功能

把course-comment.html粘贴到templates下
配置url和初步的view.py:

 #评论
    url(r'^(?P<course_id>\d+)/comment/$',CourseCommentView.as_view(),name='comment'),

view.py:

#评论模块
class CourseCommentView(LoginRequiredMixin,View):
    login_url = '/login/'  # 进入该视图类时,如果用户没有登陆,就跳转到login进行登录
    def get(self, request,course_id,*args, **kwargs):
        return render(request,'course-comment.html')

对前端页面代码优化(模板继承)

上一步中已经可以运行了,但是由于video和comment相当于是在一个页面的壳中,所以comment页面的数据是虚假的,那么comment的页面也需要video页面的数据。



解决:
把这两块的div从video复制到comment中即可,再把CourseLessonView类的视图函数复制到CourseCommentView类中即可。
运行:
点击flask后:



点击评论:

加载评论

首先这个评论是在用户操作的CourseComments类中的:



先在xadmin中添加一条数据:



在后端CourseCommentView类中:
     #加载数据库中评论
        comments = CourseComments.objects.filter(course=course)      #查询有关该课的评论

并返回comments到前端页面。
前端页面进行数据绑定:



运行:


发表评论

也就是:



上一步我们把数据库中的课程对应的评论加载出来了,但是怎么添加评论呢?
这时候要用到ajax请求进行完成。
在comment页面中加入js的插槽,在插槽中写ajax请求。

{% block custum_js %}
    <script type="text/javascript">
        //添加评论
        $(document).ready(function () {
            $('#js-pl-submit').on('click', function () {
                var comments = $("#js-pl-textarea").val()
                if (comments == "") {
                    alert("评论不能为空")
                    return
                }
                $.ajax({
                    cache: false,
                    type: "POST",
                    url: "{% url 'op: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 = "{% url 'login' %}";
                            } else {
                                alert(data.msg)
                            }

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

分析:
获取按钮id的点击是事件(#js-pl-submit),在该点击事件中获取输入框(#js-pl-textarea)的值,判断如果值为空,也就是用户没有填写,那么弹出“评论不能为空”,并且返回。
否则发起ajax请求,使用post请求,提交地址为op/comment(因为这是增加operations数据库的用户评论表),所以在operations app中接收,传输数据为课程id和评论信息comments,成功后,通过staus判断接受是否成功:如果用户未登录,那么跳转到login页面,登陆了但是status为fail,那么弹出错误信息,status为success时说明成功,刷新页面,加载新的数据。
在operations/view.py:

#发表评论
class CommentView(View):

    def post(self, request, *args, **kwargs):
        # 先判断用户是否登录
        if not request.user.is_authenticated:
            return JsonResponse({
                'status': 'fail',
                'msg': '用户未登录'
            })
        #实例化表单
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            comments = comment_form.cleaned_data['comments']
            course = comment_form.cleaned_data['course']

            ccmodel = CourseComments()
            ccmodel.comments = comments
            ccmodel.user = request.user
            ccmodel.course = course
            ccmodel.save()
            return JsonResponse({
                'status': 'success',
                'msg': '评论成功'
            })
        else:
            return JsonResponse({
                'status': 'fail',
                'msg': '评论参数错误'
            })

分析:
首先还是要判断是否登录,然后进行获取表单的值,存入数据库,返回相应的status和msg。
运行:



点击发表评论:


视频页面

course-play.html:
使用模板那继承:



在video页面跳转链接修改连接后在复制过来。
配置url和video页面跳转链接


# 视频播放
    url(r'^(?P<course_id>\d+)/video/(?P<video_id>\d+)$', CourseVideoView.as_view(), name='video'),

view.py:

#视频播放
class CourseVideoView(LoginRequiredMixin,View):
    login_url = '/login/'  # 进入该视图类时,如果用户没有登陆,就跳转到login进行登录
    '''
    章节信息的展示
    '''

    def get(self, request, course_id, video_id, *args, **kwargs):
        course = Course.objects.get(id=int(course_id))

        # 查询视频信息
        video = Video.objects.get(id=int(video_id))

        # 该课的同学还学过
        # 查询当前用户都学了那些课
        user_courses = UserCourse.objects.filter(course=course)
        user_ids = [user_course.user.id for user_course in user_courses]
        print(user_ids)
        # 查询这个用户关联的所有课程
        all_courses = UserCourse.objects.filter(user_id__in=user_ids).order_by("-course__click_nums")[:5]
        # 过滤掉当前课程
        related_courses = []
        for item in all_courses:
            if item.course.id != course.id:
                related_courses.append(item.course)

        # 查询资料信息
        course_resource = CourseResource.objects.filter(course=course)
        return render(request, 'course-play.html',
                      {"course": course,
                       "course_resource": course_resource,
                       "related_courses": related_courses,
                       "video":video,
                       })

这个view中的内容比章节view多接受一个参数video_id,并根据id查询有关视频信息。
在前端进行绑定:


相关文章

网友评论

      本文标题:2020-05-19--Django项目17--课程章节的评论,

      本文链接:https://www.haomeiwen.com/subject/qjsiohtx.html