Development of video on demand website based on django step10 background comment management function

Keywords: Python Database

In this lecture, we will talk about the comment management function. Each item in the database is from the user's comments. Therefore, the comment management in the background only has the comment list and comment deletion function, without adding comments or editing comments.

As usual, let's add related routes for comment management

path('comment_list/', views.CommentListView.as_view(), name='comment_list'),
path('comment_delete/', views.comment_delete, name='comment_delete'),

First is the display of comment list. We implement it by CommentListView view class, which is still implemented by inheriting ListView. The code is as follows

class CommentListView(AdminUserRequiredMixin, generic.ListView):
    model = Comment
    template_name = 'myadmin/comment_list.html'
    context_object_name = 'comment_list'
    paginate_by = 10
    q = ''

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super(CommentListView, self).get_context_data(**kwargs)
        paginator = context.get('paginator')
        page = context.get('page_obj')
        page_list = get_page_list(paginator, page)
        context['page_list'] = page_list
        context['q'] = self.q
        return context

    def get_queryset(self):
        self.q = self.request.GET.get("q", "")
        return Comment.objects.filter(content__contains=self.q).order_by('-timestamp')

The display of comment list is realized by inheriting ListView, paging function is realized by get ﹣ context ﹣ data(), and search function is realized by get ﹣ queryset().

The effect is as follows

Next, we will continue to implement the deletion function, which is relatively simple. You only need to pass the video [ID] to the deletion interface through ajax. The ajax code is located in static / JS / myadmin / comment [list. JS. The interface for deleting comments is API [comment] delete, which will be called to comment [delete] finally. The code is as follows

def comment_delete(request): 
    comment_id = request.POST['comment_id']
    instance = Comment.objects.get(id=comment_id)
    return JsonResponse({"code": 0, "msg": "success"})

The logic is still clear, that is, first get the id of the comment, then get the comment, and finally delete it by instance.delete().

Posted by Cynix on Mon, 02 Dec 2019 11:43:38 -0800