Django的。如何将帖子置于for循环中,其中每个帖子都有一个点赞按钮,如果用户已经喜欢该帖子,则显示一个不喜欢的按钮?

时间:2019-07-18 05:36:06

标签: django ajax

我正在尝试在for循环中打印博客文章,并允许用户喜欢该文章。如果用户已经喜欢该帖子,如何显示不喜欢的按钮?当我尝试将喜欢的部分模板放入for循环中时,即使用户已经喜欢该帖子,每个按钮也都设置为“喜欢”。

views.py

def view_post(request, id=None):
    post = get_object_or_404(Post, id=id)
    user = User.objects.get(id=post.author.id)
    userProfile = UserProfile.objects.get(pk=user.pk)
    is_liked = False
    if post.likes.filter(id=request.user.id).exists():
        is_liked = True
    context = {
        'post': post, 
        'userProfile': userProfile,
        'is_liked': is_liked,
    }
return render(request, "post/post.html", context)

def like_post(request, id=None):
    post = get_object_or_404(Post, id=request.POST.get('post_id'))
    is_liked = False
    if post.likes.filter(id=request.user.id).exists():
        post.likes.remove(request.user)
        is_liked = False
    else:
        post.likes.add(request.user)
        is_liked = True
    context = {
        'post': post,
        'is_liked': is_liked,
    }
    if request.is_ajax():
        html = render_to_string('like_section.html', context, request=request)
return JsonResponse({'form': html})

类似模板

{% if request.user.is_authenticated %}
    <form action="" method="POST">
      {% csrf_token %}
      {% if is_liked %}
        <button type="submit" id="like" name="post_id" value="{{ post.id }}" class="btn btn-danger">Dislike</button>
      {% else %}
        <button type="submit" id="like" name="post_id" value="{{ post.id }}" class="btn btn-primary">Like</button>
      {% endif %}
    </form>
{% endif %}

AJAX

<script type="text/javascript">
  $(document).ready(function(event){

    $(document).on('click', '#like', function(event){
      console.log("i'm clicked");
      event.preventDefault();
      var pk = $(this).attr('value');
      var url = "/post/like/";

    // Construct the full URL with "id"
    var theUrl = url + pk;
      $.ajax({
        type: 'POST',
        url: theUrl,
        data: {post_id: pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
        dataType: 'json',
        success: function(response){
          $('#'+pk).html(response['form'])
          console.log($('#'+pk).html(response['form']));
        },
        error: function(rs, e){
          console.log(rs.responseText);
        },
      });
    });
  });
</script>

1 个答案:

答案 0 :(得分:0)

解决方案非常简单,您要包含没有任何实例的模板。您正在尝试访问不存在的is_liked。因此,您总会得到else部分(= Like)。

尝试使用withsee the include docs)将发布实例移交给模板:

{% for post in posts %}
    <a href="/post/{{post.id}}/"><p>"{{ post.title }}"</p></a>
    <div id="{{post.id}}"> {% include 'like_section.html' with post=post %} </div>
{% endfor %}
{% if request.user.is_authenticated %}
    <form action="" method="POST">
      {% csrf_token %}
      {% if post.is_liked %}
        <button type="submit" id="like" name="post_id" value="{{ post.id }}" class="btn btn-danger">Dislike</button>
      {% else %}
        <button type="submit" id="like" name="post_id" value="{{ post.id }}" class="btn btn-primary">Like</button>
      {% endif %}
    </form>
{% endif %}