[Fixed]-How to apply ajax call to all model objects in DJANGO

1πŸ‘

in views.py

def detail(request):
    return render(request, 'detail.html', {'posts': Post.objects.all()})

def upvote(request, post_id):
   if request.method == "POST":
       p = get_object_or_404(Post, pk=post_id)
       p.upvote += 1
       p.save()
       return JsonResponse({'count':p.upvote })
   return JsonResponse({})

in detail.html:

{% for post in posts %}
     <a href='{% url 'upvote-detail' post.id %}' id='up_voite'>Up voite <span id='voite_count'> {{ post.upvote }} </span> </a>
 {% endfor %}

<script>
    $(function(){
       $('#up_voite').click(function(e) {
          e.preventDefault();
          $.post($(this).attr('href'), function(data) {
              $(this).find('span').html(data.upvote);
          });
       });
    });
</script>

code is not checked

πŸ‘€comalex3

0πŸ‘

Try this:

def upvote(request, post_id):
    p = get_object_or_404(Post, pk=post_id)
    errors = []
    data = {}
    try:
        p.upvote += 1
        p.save()
        data = {
            'success': 1,
        }
    except:
        errors.append(['There was an error'])
        data = {
            'success': 0,
            'errors':errors,
        }
    return HttpResponse(json.dumps(data))
πŸ‘€chandu

Leave a comment