Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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
XML
<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:
VB
class Like(models.Model):
    user = models.ManyToManyField(User, related_name='likes')
    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')
Posted
Comments
Ashish Tyagi 40 9-Apr-14 12:54pm    
Like model looks good, can you share other Post model, also the HTTP request and response data as well? That will help to figure out the issue.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900