试图在模型上创建一个Like按钮

时间:2016-07-03 10:03:49

标签: javascript html django

我几天来一直在努力为模型实现类似的按钮。我有一个像这样的模型

class Feed(models.Model):
    user=models.ForeignKey(User,on_delete=models.CASCADE,related_name='feeds')
    text=models.TextField(blank=False,max_length=500)
    user_concerns=models.ManyToManyField(User,related_name="likes",blank=True)
@property
    def total_concerns(self):
        return self.user_concerns.count()

我试图让用户在前端喜欢一个Feed。所以我有这个视图和网址

#urls.py
urlpatterns = [
 url(r'^like/$', views.like, name='like'),]

#views.py
@require_POST
def like(request):
    if request.method == 'POST':
        user = request.user
        slug = request.POST.get('slug', None)
        feed = get_object_or_404(Feed, slug=slug)

        if feed.user_concerns.filter(id=user.id).exists():
            # user has already liked this company
            # remove like/user
            feed.user_concerns.remove(user)
            message = 'You disliked this'
        else:
            # add a new like for a company
            feed.user_concerns.add(user)
            message = 'You liked this'

    ctx = {'likes_count': feed.total_concerns, 'message': message}
    # use mimetype instead of content_type if django < 5
    return HttpResponse(json.dumps(ctx), content_type='application/json')  

和模板

<p>{{feed_detail.text|linebreaks}} </p>
          <p> {{feed_detail.total_concerns}} concern{{feed_detail.total_concerns|pluralize:'s'}}</p>
           <p> {{feed_detail.pub_date|naturaltime|capfirst}} </p>
                    <input type="button" id="like" name="{{feed_detail.slug}}" value="Like" />

<script>

$('#like').click(function(){

      $.ajax({

               type: "POST",
               url: "{% url 'like' %}",
               data: {'slug': '{{feed_detail.slug}}' , 'csrfmiddlewaretoken': '{{ csrf_token }}'},
               dataType: "json",
               success: function(response) {
                      alert(response.message);
                      alert('Company likes count is now ' + response.likes_count);
                },
                error: function(rs, e) {
                       alert(rs.responseText);
                }
          }); 
    })

</script>

它根本没有显示任何错误。它显示按钮但没有对点击进行任何操作,请帮助我,因为我对此很疯狂

1 个答案:

答案 0 :(得分:1)

也许你没有包含jQuery。

首先,在settings.py中定义静态目录。

STATIC_URL = '/static/'

在app文件夹中创建一个静态文件夹。将jQuery js文件放在app_name / static / app_name / js中。然后在你的模板中:

<head>
{% load staticfiles %}    
<script src="{% static "app_name/js/bootstrap.min.js" %}"></script>   
</head>