我跟随Tango使用Django的教程添加了like按钮。我认为它有效,但它似乎只适用于列表中的第一个模型实例。你看,我有一个视图,显示列表中的所有对象。我的代码如下所示:
views.py
def content_list(request):
posts = Post.objects.all()
return render(request, 'app/content_list.html', {'posts' : posts})
models.py
class Post(models.Model):
user = models.ForeignKey(User, related_name = 'user_posts')
title = models.CharField(max_length = 140)
votes = models.IntegerField(default = 0)
content_list.html - 模板
{% for post in posts %}
<h1>{{post.title}}</h1>
<p><strong id="like_count">{{post.votes}}</strong> points</p>
{% if request.user.is_authenticated %}
<button id="likes" data-post-id="{{post.id}}" class="btn btn-purple" type="button">
<span>Upvote</span>
</button>
{% endif %}
{% endfor %}
在 views.py 中,我有另一个处理后期喜欢的函数:
@login_required
def like_post(request):
post_id = None
# Getting the id of the post from the template
if request.method == 'GET':
post_id = request.GET['post_id']
likes = 0
if post_id:
post = Post.objects.get(id = int(post_id))
if post:
likes = post.votes + 1
post.votes = likes
post.save()
return HttpResponse(likes)
最后,我的ajax文件执行实际工作:
$('#likes').click(function(){
var p_id;
p_id = $(this).attr("data-post-id");
$.get('/like_post/', {post_id: p_id}, function(data){
$('#like_count').html(data);
$('#likes').hide();
});
});
我的app文件夹中的 urls.py 在网址格式中包含以下行:
# Liking a post
url(r'^like_post/$', views.like_post, name='like_post'),
我错过了什么?其他帖子的连根拔按钮也不会隐藏,因为我的ajax代码。我该如何解决这个问题?
谢谢!
答案 0 :(得分:1)
通过应用评论中提到的内容,您的服务器代码可能会变为:
{% for post in posts %}
<h1>{{post.title}}</h1>
<p><strong id="like_count">{{post.votes}}</strong> points</p>
{% if request.user.is_authenticated %}
<button data-post-id="{{post.id}}" class="likes btn btn-purple" type="button">
<span>Upvote</span>
</button>
{% endif %}
{% endfor %}
javascript部分现在是:
$('.likes').click(function(){
var p_id;
p_id = $(this).attr("data-post-id");
$.get('/like_post/', {post_id: p_id}, function(data){
$('#like_count').html(data);
$(this).hide();
});
});