Django-like按钮不会更新喜欢的内容

时间:2017-04-19 06:58:05

标签: jquery python ajax django

我正在接近完成Tango与Django教程,我在家附近,在制作一个'喜欢'按钮的过程中:

http://www.tangowithdjango.com/book17/chapters/ajax.html#add-a-like-button 应该发生的是:

  

单击按钮时,会根据我们的URL发出AJAX请求   映射,这会调用更新的like_category视图   类别并返回新的喜欢数量。当AJAX请求时   收到它更新页面部分的响应,即文本和   按钮。 #likes按钮被隐藏。

我的按钮在那里,可以点击,但点击后不会隐藏,也不会实际增加喜欢的数量,我不知道为什么,我在前面的介绍章节中成功创建了按钮。

这些是相关的代码段(但是如果有一些我遗漏的内容可能会有所帮助,请告诉我们:

views.py

@login_required

def like_category(request):

    cat_id = None
    if request.method == 'GET':
        cat_id = request.GET['post_id']

    likes = 0
    if cat_id:
        cat = Post.objects.get(id=int(cat_id))
        if cat:
            likes = cat.likes + 1
            cat.likes =  likes
            cat.save()

    return HttpResponse(likes)

兰戈-ajax.js

    $('#likes').click(function(){
        var catid;
        catid = $(this).attr("data-catid");
        $.get('/rango/like_category/', {category_id: catid}, function(data){
                   $('#like_count').html(data);
                   $('#likes').hide();
        });
    });

about.html

{% extends 'base.html' %}
{% load static %}
{% block body_block %}
<p>

<strong id="like_count">{{ post.likes }}</strong> people like this category

{% if user.is_authenticated %}
        <button id="likes" data-catid="{{post.id}}" class="btn btn-primary" type="button">
        <span class="glyphicon glyphicon-thumbs-up"></span>
        Like
        </button>
{% endif %}
</p>

<script type="text/javascript" src="{% static 'js/rango-ajax.js' %}"></script>
{% endblock %}
{% endblock %}

models.py

class Post(models.Model):
    post = models.TextField()
    user = models.ForeignKey(User)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    likes = models.IntegerField(default=0)

    def __unicode__(self):
        return self.name
    def __str__(self):
        return self.post

当我点击“赞”按钮时,这是我的控制台显示的内容:

Not Found: /assets/js/ie10-viewport-bug-workaround.js [19/Apr/2017 06:55:29] "GET /assets/js/ie10-viewport-bug-workaround.js HTTP/1.1" 404 5180 [19/Apr/2017 06:55:29] "GET /static/fonts/glyphicons-halflings-regular.woff HTTP/1.1" 404 1730 [19/Apr/2017 06:55:29] "GET /static/fonts/glyphicons-halflings-regular.ttf HTTP/1.1" 404 1727

0 个答案:

没有答案