我正在努力实现类似按钮的工作。我想我有它的代码,但我不知道如何在模板中实现它。
(这是制作类似按钮的正确方法,所以如果有其他人看到这个问题,他们也可以获得帮助,以获得像按钮一样的最佳方式)
知道我知道我必须在某个时候使用Ajax,但我现在的重点只是让那些喜欢的东西显示在like按钮旁边。
models.py
class Posts(models.Model):
post = models.CharField(max_length=3000) #probably switch to a textfield
sender = models.ForeignKey(User, related_name='sent_the_post', null=True, blank=True)
sent = models.DateTimeField(auto_now_add=False, auto_now=False, null=True, blank=True)
read = models.DateTimeField(auto_now_add=False, auto_now=False, null=True, blank=True)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
class Meta:
ordering = ['-timestamp']
def __unicode__(self):
return self.post
class Like(models.Model):
liked_users = models.ManyToManyField(User, null=True, blank=True, related_name='liked_users')
post = models.ForeignKey(Posts, null=True, blank=True)
def __unicode__(self):
return 'like'
views.py
def like(request):
if request.method == 'POST':
post_id = request.POST['post_id']
try:
post = Post.objects.get(id=post_id)
except:
post = None
if post:
post_to_like, created = Like.objects.get_or_create(post=post)
if request.user in post_to_like.liked_users:
#this removes the user
post_to_like.liked_users.remove(request.user)
else:
post_to_like.liked_users.add(request.user)
post_to_like.save()
like_count = post_to_like.liked_users.count() #returns number of users in the manytomanyfield
return render_to_response('posts/wall.html', locals(), context_instance=RequestContext(request))
wall.html模板 - 以下是post div
<form action='' method='post'> {% csrf_token %}
<input name='post_id' value='{{ post.id }}' type='hidden' />
<input class='btn btn-default' type='submit' value='Like'>
</form>
{{ .like_count }}
答案 0 :(得分:0)
只需添加模板中按钮旁边的喜欢数量:
<input class='btn btn-default' type='submit' value='Like' /> {{post.like_set.count}} likes
或使用pluralisation template tag(以便获得1 like
和2 likes
等):
{% with post.like_set.count as likes %}
<input class='btn btn-default' type='submit' value='Like'> {{likes}} like{{likes|pluralize}}
{% endwith %}