如何在Django网站中使用Ajax添加评论?

问题描述

如何在不刷新页面的情况下在Django网站中添加评论

这是我的代码

VIEW.PY

@login_required
def comments(request,post_id):
    """Comment on post."""
    post = get_object_or_404(Post,id=post_id)
    user = request.user
    comments = Comment.objects.filter(post=post).order_by('-date')#comment
    if request.method == 'POST':#Comments Form
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.user = user
            comment.save()
            messages.success(request,'Comment has been added successfully.')
            return HttpResponseRedirect(reverse('core:comments',args=[post_id]))
    else:
        form = CommentForm()
    template = loader.get_template('post/comments.html')
    context = {'post':post,'form':form,'comments':comments,}
    return HttpResponse(template.render(context,request))

COMMENTS.HTMl

表单部分:

 <div class='commentsection' >

<strong>
<form  action="{% url 'core:comments' post.id %}"  method='post' id=comment-form >
{% csrf_token %}
 {% bootstrap_form form %}

 </form>
 <br/>
 <br/>
 </strong>
</div>

评论部分:

{% for comment in comments %}

 <div class="card mb-3" style="width: 30rem;">
   <div class="row no-gutters">
         <small> <a style="color: black;"  href="{% url 'core:user_profile' comment.user %}"><img src="{{comment.user.profile.profile_pic.url}}" width=50 height=50 class="profile-image img-circle " style="object-fit: cover; float: auto; "><strong style="font-size: 18px;" >   @{{comment.user}} </strong></a> </small> <small><span class="glyphicon glyphicon-time"></span> {{ comment.get_date }}</small>
     </div>
       <div class="card-body"  style="width:100%; padding-left:20%; margin-top:-8%; word-break: break-all; color:black; " >
         <h5 class="card-text">

         {{ comment.comment }}</h5>
         <small ><a href="{% url 'core:replies' comment.id %}"> Replies </a> [{{comment.total_replies}}] </small

       </div>
     </div>
 </div>
<br/><br/>
 {% empty %}
<center>
 No commnets
 </center>

 {% endfor %}

我的问题:

  1. 添加评论而不刷新页面
  2. 评论部分自动添加添加评论,而无需刷新页面

谢谢!

解决方法

您已经正确地推测出这是一个AJAX问题,尽管您现在也可以使用websocket。传统的django解决方案将带有AJAX回调。为您编写简短的代码,我可以提供形式化的解决方案(概述):

  1. 向您的站点添加一个视图,该视图以JSON(或XML或其他可序列化的格式)返回给定日期时间的新注释列表(您可以将其作为GET参数或POST参数传递给视图) 。
  2. 将Javascript添加到您的页面,该页面会定期用新的评论请求轮询服务器。如果返回任何内容,则必须为您动态地将这些注释添加到DOM。

您的第二个请求(自动添加新评论)取决于您是否要使用网络套接字。如果您使用websocket,则可以,当有新评论到达时,服务器可以通过该套接字通知您的页面。但是,如果您要坚持使用AJAX,则它取决于轮询间隔(这是开发Websocket且有用的一大原因)。

在线上有无数的教程和操作方法,介绍如何编写Javascript来获取数据和动态更新DOM,以及如何使用Websocket。