Django+Ajax: div update after post -


i'm new @ ajax , django. have ajax button adds "likes" database. besides button, template displays total number of likes. button works can't figure out how update "like-count" div because calling {{ post.likes.count }} displays old result. i'm guessing that's due caching? around declared like_count variable in view , add +=1 when liked.

how make {{ like_count }} work in template? using

return render(request, 'app/blog.html', {'like_count': like_count}) 

sends me blank page instead of updating div.

view:

@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.objects.filter(user=user, content_type=content, object_id=post_id).delete()             like_count -=1          else:             # add new             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})  

template:

<div id="like-count">like {{ post.likes.count }}</div> <form method="post" action="{% url 'like' %}" id="like-form">          {% csrf_token %}          <input type="hidden" id="post_id" name="post" class="hidden_id" value="{{ post.pk }}" />   <input type="hidden" id="user_id" name="user" class="hidden_id" value="{{ user.pk }}" />   <button class="btn">like</button>          </form>  <script type="text/javascript">     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();     }); </script> 

assuming django 1.7+

def like(request):     if request.is_ajax():       ... make sure return gets used     return jsonresponse({'like_count':somevar}) 

on client.. like:

  $.ajax({             ...             success: function(response) {                 document.getelementbyid('like-count').innerhtml = response['like_count'];             }         }) 

Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -