Change a Django Model with Javascript

Viewed 2285

So i want to change the Django Module "Post.upvotes" to +1 everytime someone presses the button without reloading the Page.

I think its called Ajax.

JS:

$('.buttonclass').click(function(){
    var pk;
    pk = $(this).attr("data-pk");
});

html:

<span data-pk="{{post.pk}}" class="buttonclass"></span>

my_views.py

def upvote(request):
    pk = None
    if request.method == 'GET':
        pk = request.GET['pk']     
    obj = models.Post.objects.get(pk=pk)
    obj.upvotes = obj.upvotes +1
    obj.save()
    return redirect("index") #without this

urls.py

 url(r"upvote/(?P<pk>\d+)/$", views.upvote, name="upvote"),

post:

class Post(models.Model):
    upvotes = models.IntegerField(default = 0)

So how exactly can i do this?

1 Answers

You need to use ajax for this issue.

Create a separate route for this URL. (Preferable use post method)

my_views.py

from django.http import HttpResponse
def upvote(request):
    pk = request.GET['pk']     
    obj = models.Post.objects.get(pk=pk)
    obj.upvotes = obj.upvotes +1
    obj.save()
    response_data = {'success':1}
    return HttpResponse(json.dumps(response_data), content_type="application/json")

your js

$('.buttonclass').click(function(){
    var pk = $(this).attr("data-pk");
    $.get('[YOUR_URL_HERE]'+/pk,function (r){console.log(r);})
});
Related