评论系统切换到ajax,因此不会转到其他页面

时间:2019-06-01 17:49:34

标签: javascript python ajax django

我能够用python,django编写注释系统。但要发表评论,用户必须移至其他网址。我不希望用户移动到其他页面来编写,编辑,删除评论。我用谷歌搜索,似乎必须使用ajax,但不确定。有人可以指导我怎么做吗?

views.py

@login_required
def comment_new(request, post_pk):
    post = get_object_or_404(Post, pk=post_pk)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.author = request.user
            comment.save()
            return redirect('home')
    else:
        form = CommentForm()
    return render(request, 'community/comment_form.html', {
        'form':form,
        })

@login_required
def comment_edit(request, post_pk, pk):
    #post = get_object_or_404(Post, pk=post_pk)
    comment = get_object_or_404(Comment, pk=pk)
    if comment.author != request.user:
        return redirect(comment.post)
    if request.method == 'POST':
        form = CommentForm(request.POST, instance=comment)
        if form.is_valid():
            comment = form.save()
            return redirect(comment.post)
    else:
        form = CommentForm(instance=comment)
    return render(request, 'community/comment_form.html', {
        'form':form,
        })

@login_required
def comment_delete(request, post_pk, pk):
    comment = get_object_or_404(Comment, pk=pk)
    if comment.author != request.user:
        return redirect(comment.post)
    if request.method == 'POST':
        comment.delete()
        return redirect(comment.post)
    return render(request, 'community/comment_confirm_delete.html', {
        'comment':comment,
        })

models.py

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    author = models.ForeignKey(settings.AUTH_USER_MODEL,  on_delete=models.CASCADE)
    message = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-id']

    def get_edit_url(self):
        return reverse('comment_edit', args=[self.post.pk, self.pk])

    def get_delete_url(self):
        return reverse('comment_delete', args=[self.post.pk, self.pk])

urls.py

urlpatterns = [
    path('', PostListView.as_view(), name='community-home'),
    path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
    path('post/<int:post_pk>/comment/new',views.comment_new, name='comment_new'),
    path('post/<int:post_pk>/comment/<int:pk>/edit',views.comment_edit, name='comment_edit'),
    path('post/<int:post_pk>/comment/<int:pk>/delete',views.comment_delete, name='comment_delete'),

我的html

<a href="{% url 'comment_new' post.id %}">hello</a> 

  <ul>
    {% for comment in post.comment_set.all %}
    <li>
      {{comment.message}} by {{comment.author}} at {{comment.created_at}}
      {% if comment.author == request.user %}
      <a href="{{ comment.get_edit_url }} ">
        edit
      </a>
      <a href="{{comment.get_delete_url}}">delete</a>
      {% endif %}
    </li>
    {% endfor %}
  </ul>

forms.py

from django import forms
from .models import Comment

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ['message']

1 个答案:

答案 0 :(得分:0)

您必须显示html。如果您愿意,我会为您执行ajax代码。

首先,您需要确保脚本中包含jquery。将此放在头部之后和身体之前

  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

接下来,您必须通过onclick调用AJAX请求的javascript函数。

   {% for comment in post.comment_set.all %}

      <a href=onclick="get_delete({{comment.id}})">delete</a>

    {% endfor %}

这是您调用的javascript函数:

function get_delete(n){

var patch = '{% url "comment_delete" %}'
var post_data = {
  'csrfmiddlewaretoken':"{{ csrf_token }}",
 'iddy':n,}

$.ajax({
  type: "POST",
  url: patch,
  data:post_data,
  datatype:'json',
success: function(data){
console.log(data)
return
}

})}

将您的网址路径更改为。

path('post/commentdelete',views.comment_delete, name='comment_delete')

最后,在视图中

def comment_delete(request):
    if request.POST:
        response_json = request.POST
        response_json = json.dumps(response_json)
        data = json.loads(response_json)
        comment = get_object_or_404(Comment, id=data['iddy'])
        if comment.author != request.user:
            msg = "you didnt write this comment"
            data = {'msg':msg}
        else:
             comment.delete()
             msg = "deleted"
             data = {'msg':msg}
   return JsonResponse(data, safe=False)