我想做一个点赞按钮,一按该按钮,模型的点赞属性将增加1。该模型如下所示:
class Post(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length = 200)
text = models.TextField()
created_date = models.DateTimeField(default = timezone.now)
likes = models.IntegerField(default=0)
tags = models.CharField(max_length = 50, default = '' )
def process_likes(self):
print(self.likes)
self.likes += 1
def split_tags(self):
return self.tags.split()
def get_absolute_url(self):
return reverse('blog:post_list')
def __str__(self):
return self.title
我在其中调用该方法的视图中的函数看起来像这样:
def print_hi(request, pk):
print('Hi there!')
post = get_object_or_404(Post, pk=pk)
post.process_likes()
return redirect('blog:post_detail', pk=post.pk)
该视图功能的网址对应:
path('print/<int:pk>', views.print_hi, name='print_hi'),
还有我在其中调用url的锚点来调用函数:
<a href="{% url 'blog:print_hi' pk=post.pk %}" class="btn">Soy un botón</a>
process_likes方法是负责增加点赞计数器的方法,但是当我按下按钮调用函数时,它不会增加计数吗?我该怎么解决?
答案 0 :(得分:1)
致电post
后,您必须保存process_likes()
:
def print_hi(request, pk):
print('Hi there!')
post = get_object_or_404(Post, pk=pk)
post.process_likes()
post.save()
return redirect('blog:post_detail', pk=post.pk)