Django: How To Like An Object With Ajax
Here's my View, class ObjLike(RedirectView): def get_redirect_url(self, *args, **kwargs): id = self.kwargs.get('id') obj = get_object_or_404(Data, id=id) user = self.re
Solution 1:
to like an object with ajax calls do this first in html we want to make a like button:
<button id="like">Like!</button>
the add a script that contain the ajax:
<script>
$(document).ready(function() {
$("#like").click(function(event){
$.ajax({
type:"POST",
url:"{% url 'like' Obj.id %}",
success: function(data){
confirm("liked")
}
});
returnfalse;
});
});
</script>
the we add the like url to the urlpatterns list:
url(r'like/obj/(?P<pk>[0-9]+)/', views.like, name="like"),
adding the view :
from django.views.decorators.csrf import csrf_exempt
@csrf_exemptdeflike(request, pk)
obj = Obj.objects.get(id=pk)
obj.likes += 1
obj.save()
return HttpResponse("liked")
Note: you can customize the like view to check if user liked already
Post a Comment for "Django: How To Like An Object With Ajax"