как добавить javascript для подобного / непохожего в django? - PullRequest
0 голосов
/ 14 июля 2020

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/")

дома. 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. Любая помощь будет оценена по достоинству.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...