使用Django + Ajax添加Like按钮

时间:2015-10-10 20:21:05

标签: javascript jquery python ajax django

您好我创建了我的第一个项目,如stackoverflow(问答)。我使用Tango和Django http://www.tangowithdjango.com/book17/chapters/ajax.html的这个guid来添加带有ajax的按钮。没有什么可恶的。在控制台中看不到任何请求。我是Django中的菜鸟,这是我第一次遇到jquery。

apps/questions/models:

class Answer(models.Model):

    text = models.TextField()
    date = models.DateTimeField(default=datetime.datetime.now)
    likes = models.IntegerField(default=0)
    resolve = models.IntegerField(default=0)
    author = models.ForeignKey(CustomUser)
    question = models.ForeignKey(Question)

apps/questions/views:

@login_required
def add_like(request):

    ans_id = None
    if request.method == 'GET':
        ans_id = request.GET['answer_pk']

    likes = 0
    if ans_id:
        ans = Answer.objects.get(id=(int(ans_id)))
        if ans:
            likes = ans.likes + 1
            ans.likes = likes
            ans.save()

    return HttpResponse(likes)

apps/questions/ulrs: 
url:
   url(r'add_like/$', views.add_like, name='add_like'),

 question.html:
    {% for answer in answers %}
    <div class="container-fluid no-padding">
        {{ answer.text }}   
    </div>
    <div class="container-fluid  author-question">
    <p>posted: {{ answer.date.day|stringformat:"02d" }}.{{ answer.date.month|stringformat:"02d"}}.{{ answer.date.year}}</p>
    <p>by: {{ answer.author.username }}</p>
    </div>
    {% if user.is_authenticated %}
    <button class="btn btn-default" type="button" id="likes" data-ansid="{{ answer.id }}">
        like | <strong id="like_count">{{ answer.likes }}</strong>
    </button>
    {% endif %}

js/ajax.js:

    $('#likes').click(function(){
    var ansid;
    ansid = $(this).attr("data-ansid");
            $.get('/questions/add_like/', {answer_id: ansid}, function(data){
        $('#like_count').html(data);
    $('#likes').hide();
});
});

1 个答案:

答案 0 :(得分:1)

由于您在for循环中创建按钮,并以相同的方式命名它们,因此页面上有多个具有相同ID的元素。因此,您会得到不可预测的结果。您应该为每个按钮指定自己的ID,或者更改jQuery选择器以根据相应的类选择按钮。

例如,您可以:

{% for answer in answers %}
    <div class="container-fluid no-padding">
        {{ answer.text }}   
    </div>
    <div class="container-fluid  author-question">
    <p>posted: {{ answer.date.day|stringformat:"02d" }}.{{ answer.date.month|stringformat:"02d"}}.{{ answer.date.year}}</p>
    <p>by: {{ answer.author.username }}</p>
    </div>
    {% if user.is_authenticated %}
    <button class="btn btn-default likes-button" type="button" data-ansid="{{ answer.id }}">
        like | <strong id="like_count">{{ answer.likes }}</strong>
    </button>
    {% endif %}
{% endfor %}

然后是javascript

$('.likes-button').click(function(){
    var ansid;
    ansid = $(this).attr("data-ansid");
            $.get('/questions/add_like/', {answer_id: ansid}, function(data){
        $('#like_count').html(data);
    $('#likes').hide();
});
});