title: Django+Ajax: div update after post
body: <p>I'm new at Ajax and Django. I have an Ajax like button that adds "likes" to my database. Besides the button, my template also displays the total number of likes. The button works but I can't figure out how to update the "like-count" div because calling <code>{{ post.likes.count }}</code> displays the old result. I'm guessing that's due to caching? To get around this I declared a like_count variable in my view and then add +=1 when liked. </p>
  
  <p>How do I make <code>{{ like_count }}</code> work in my template? Using </p>
  
  <pre><code>return render(request, 'app/blog.html', {'like_count': like_count})
  </code></pre>
  
  <p>sends me to blank page instead of updating the div.</p>
  
  <p>View:</p>
  
  <pre><code>@login_required
  def like(request):
      if request.is_ajax():
          user = request.user
          post_id = request.POST.get('post', None)
          content = ContentType.objects.get_for_model(Post)
          like_count = Like.objects.filter(content_type=content, object_id=post_id).count()
  
          if Like.objects.filter(user=user, content_type=content, object_id=post_id).exists():
              # remove like
              Like.objects.filter(user=user, content_type=content, object_id=post_id).delete()
              like_count -=1
  
          else:
              # add a new like
              Like.objects.create(user=user, content_type=content, object_id=post_id)
              like_count +=1
  
      return HttpResponse()
      return render(request, 'app/blog.html', {'like_count': like_count}) 
  </code></pre>
  
  <p>Template:</p>
  
  <pre><code>&lt;div id="like-count"&gt;Like {{ post.likes.count }}&lt;/div&gt;
  &lt;form method="post" action="{% url 'like' %}" id="like-form"&gt;
           {% csrf_token %}
           &lt;input type="hidden" id="post_id" name="post" class="hidden_id" value="{{ post.pk }}" /&gt;
    &lt;input type="hidden" id="user_id" name="user" class="hidden_id" value="{{ user.pk }}" /&gt;
    &lt;button class="btn"&gt;Like&lt;/button&gt;
           &lt;/form&gt;
  
  &lt;script type="text/javascript"&gt;
      var frm{{ post.id }} = $('#like-form');
      frm{{ like.id }}.submit(function (ev) {
          $.ajax({
              type: frm{{ post.id }}.attr('method'),
              url: frm{{ post.id }}.attr('action'),
              data: frm{{ post.id }}.serialize(),
              success: function (data) {
                  document.getElementById("like-count").innerHTML = {{ like_count }};
              }
          });
  
          ev.preventDefault();
      });
  &lt;/script&gt;
  </code></pre>