Django喜欢按钮ajax

时间:2017-03-30 13:53:36

标签: jquery python ajax django django-views

我一直在尝试使用ajax创建类似按钮。在我的模型中,我有一个字段调用user_like = models.ManyToManyField(settings.AUTH_USER_MODEL,                                        related_name = 'strains_liked',                                        空白= TRUE)

这是我的views.py

@login_required
@require_POST
def strain_like(request):
    strain_id = request.POST.get('id')
    action = request.POST.get('action')
    if strain_id and action:
        try:
            strain = Strain.objects.get(id=strain_id)
            if action == 'like':
                strain.user_like.add(request.user)
            else:
                strain.user_like.remove(request.user)
            return JsonResponse({'status': 'ok'})
        except:
            pass
    return JsonResponse({'status': 'ok'})

这是urls.py

url(r'^like/$', views.strain_like, name='like')

这是我的模板

{% block content %}
{{ strain.name }}

    {% with total_likes=strain.user_like.count user_like=strain.user_like.all %}
       <span class="count">
           <span class="total">{{ total_likes }}</span> like
       </span>
        <a href="#" data-id="{{ strain.id }}" data-action="{% if request.user in user_like %}un{% endif %}like" class="like">
        {% if request.user not in user_like %}
            Like
        {% else %}
            Unlike
        {% endif %}
        </a>
    {% endwith %}
{% endblock %}
<script>
var csrftoken = $.cookie('csrftoken');
function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});
    $(document).ready(function () {
$('a.like').click(function(e){
            e.preventDefault();
            $.post('{% url "strains:like" %}',
             {
                 id: $(this).data('id'),
                 action: $(this).data('action')
             },
             function(data){
                if (data['status'] == 'ok')
                {
                    var previous_action = $('a.like').data('action');
                    $('a.like').data('action', previous_action == 'like' ? 'unlike' : 'like');
                    $('a.like').text(previous_action == 'like' ? 'unlike' : 'like');

                    var previous_likes = parseInt($('span.count .total').text());
                    $('span.count .total').text(previous_action == 'like' ? previous_likes + 1 : previous_likes - 1);
                }
            }
            );
     });
    })
</script>

当我点击喜欢或不同时我在开发者工具中有这个错误

IMG with error

1 个答案:

答案 0 :(得分:1)

此动作的网址为r'^ like / $'。但是你发送了/ strain / like的请求,这是不匹配的。