如何在Django中为喜欢/不喜欢添加JavaScript?

时间:2020-07-14 15:59:54

标签: django ajax

views.py

def like(req, pk):
    post = MyPost.objects.get(pk=pk)
    PostLike.objects.create(post=post, liked_by = req.user.myprofile)
    #return HttpResponseRedirect(redirect_to="/home/")
    #if req.is_ajax():
        #html = render_to_string('Socialize/like_1.html',req=req,pk=pk)
        #return JsonResponse({'form':html})
    return HttpResponseRedirect(redirect_to="/home/")

def unlike(req, pk):
    post = MyPost.objects.get(pk=pk)
    PostLike.objects.filter(post=post, liked_by = req.user.myprofile).delete()
    return HttpResponseRedirect(redirect_to="/home/")

在home.html中:

{% if x.liked %}
<a  href="{% url 'unlike' x.id %}" id="like"><i class="fa fa-heart" aria-hidden="true"style=" color:red;font-size:36px"></i>
</a>
{% else %}
<a href="{% url 'like' x.id %}" id="like"><i class="fa fa-heart" aria-hidden="true" style="color: LightGray; font-size:25px"></i>
</a>
{% endif %}

urls.py:

 path('mypost/like/<int:pk>', views.like, name="like"),
 path('mypost/unlike/<int:pk>', views.unlike, name="unlike"),

我尝试添加脚本标签,但是我对如何实现尚不明确,请帮忙!

$(document).ready(function(event){
  $(document).on('click', '#like', function(event){
    event.preventDefault():
    var pk = $(this).attr('x.id'):
    $.ajax({
      type: 'POST',
      url:'{% url 'like' x.id%}' ,
      data: {'pk':pk, },
      dataType: 'json',
      success: function(response){
        ${'#like-section'}.html(response['form'])
        console.log(${'#like-section'}.html(response['form']));
      },
      error: function(rs,e){
      console.log(rs, responseTet);

    },
});
  });
});

此外,如何添加json响应。任何帮助将不胜感激。

0 个答案:

没有答案