The below code is for my like button. The button itself comes through on the html document where it is supposed to be. But it seems that nothing happens when clicked. I have no idea how to make the code work, so that a user can click the button, and it actually gets stored in the database.
Can anyone see some problems with my code, or something that could be done different, that would be better?
I hope my question makes sense, and that someone can help me.
Maybe something do happen, and it is just missing a type of display for that, in that case, how would I create that display?
.html
<input type="button" id="like" name="{{company_slug}}" value="Like" />
<script>
$('#like').click(function(){
$.ajax({
type: "POST",
url: "{% url 'search' %}",
data: {'slug': $(this).attr('name'), 'csrfmiddlewaretoken': '{{csrf_token}}'},
dataType: "text",
success: function(response) {
alert('You liked this')
},
error: function(rs, e) {
alert(rs.responseText);
}
});
})
</script>
models.py:
class Like(models.Model):
user = models.ManyToManyField(User, related_name=
company = models.ForeignKey(Posts)
date = models.DateTimeField(auto_now_add=True)
total_likes = models.IntegerField(default=0)
views.py:
def like(request):
vars = {}
if request.method == 'POST':
user = request.user #maybe lowercase u
slug = request.POST.get('slug', None)
like = get_object_or_404(Posts, slug=slug)
liked, created = Like.objects.create(like=like)
try:
user_liked = Like.objects.get(like=like, user=user)
except:
user_liked = None
if user_liked:
user_liked.total_likes -= 1
liked.user.remove(request.user)
user_liked.save()
else:
liked.user.add(request.user)
liked.total_likes += 1
liked.save()
return HttpResponse(simplejson.dumps(vars), mimetype='application/javascript')