weixin_33688840 2017-03-30 13:53 采纳率: 0%
浏览 17

Django的喜欢按钮ajax

I'm been trying to create like button with ajax. In my model strain i have a field call user_like = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='strains_liked', blank=True)

This is my 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'})

this is urls.py

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

and this is my templates

{% 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>

when I click to like or unlike I have this error in developer tools

IMG with error

  • 写回答

1条回答

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥30 如何降低hdfs中datanode的JVM内存用量
      • ¥15 Android URL如何转成视频/音频,可行吗?
      • ¥20 SQL数据查询,子查询
      • ¥15 c++字符串分割问题
      • ¥15 vue+uniapp
      • ¥15 android freedom
      • ¥15 关于STM32的SPI和ENDAT接口编码器通信的问题
      • ¥15 关于#pdfbox#生成的PDF文件正常,转图片中文乱码的问题,如何解决?
      • ¥15 ADS中有关DAC控件的使用问题
      • ¥15 win11如何运行geoserver