我试图创建自己喜欢的按钮,但我遇到了一些问题。
代码使用Ajax和Django,我收到一条错误消息,但我不知道出了什么问题。
这是代码,主要受this post启发。
文章\ models.py
class Article(models.Model):
user = models.ForeignKey(User, default='1')
titre = models.CharField(max_length=100, unique=True)
[... some unrelated models ...]
slug = models.SlugField(max_length=40)
likes = models.ManyToManyField(User, related_name="likes")
def __str__(self):
return self.titre
@property
def total_likes(self):
return self.likes.count()
文章\ urls.py
url(r'^like/$', views.like_button, name='like_button'),
文章\ views.py
@login_required(login_url='/user')
def like_button(request):
if request.method == 'POST':
user = request.user
id = request.POST.get('pk', None)
article = get_object_or_404(Article, pk=id)
if article.likes.filter(id=user.id).exists():
article.likes.remove(user)
else:
article.likes.add(user)
context = {'likes_count': article.total_likes}
return HttpResponse(json.dumps(context), content_type='application/json')
(正如你所看到我试图获得文章ID而不是slug)
article.html
<div>
{% for a in article %}
[... some unrelated html ...]
<input type="button" class="like" name="{{ a.id }}" value="Like" />
<p>count : {{ a.total_likes }}</p>
{% endfor %}
</div>
<script>
$('.like').click(function(){
$.ajax({
type: "POST",
url: "{% url 'like_button' %}",
data: {'pk': $(this).attr('name'), 'csrfmiddlewaretoken': '{{ csrf_token }}'},
dataType: "json",
success: function(response) {
alert('Company likes count is now ' + response.count_likes);
},
error: function(rs, e) {
alert(rs.responseText); #No Article matches the given query.
}
});
})
</script>
错误表明No Article与给定查询匹配。
为了使这项工作,我应该改变什么?
答案 0 :(得分:1)
从你的代码我可以看到&#34; id =&#34;喜欢&#34;用于for循环,因此它使多个按钮具有相同的ID。 ID必须是唯一的
尝试使用类
更改id<div>
{% for a in article %}
[... some unrelated html ...]
<input type="button" class="like" name="{{ a.id }}" value="Like" />
<p>count : {{ a.total_likes }}</p>
{% endfor %}
</div>
<script>
$('.like').click(function(){
var pk = $(this).attr('name');
$.ajax({
type: "POST",
url: "{% url 'like_button' %}",
data: {'pk': pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
dataType: "json",
success: function(response) {
alert('Company likes count is now ' + response.count_likes);
},
error: function(rs, e) {
alert('Something went wrong.'); #getting this message.
}
});
})
</script>