我正在尝试向我的网站添加喜欢的帖子系统。我已经具有喜欢和不喜欢帖子的功能,但是我无法在模板中更改按钮值。
models.py 类Post(models.Model):
file = models.FileField(upload_to='files/')
summary = models.TextField(max_length=600)
pub_date = models.DateTimeField(auto_now=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
likes = models.ManyToManyField(User, related_name='likes')
is_liked = models.BooleanField(default=False)
views.py
def likepost(request, pk):
if request.method == 'POST':
user = request.user
post = get_object_or_404(Post, pk=pk)
if post.likes.filter(id=user.id).exists():
post.is_liked = True
post.likes.remove(user)
else:
post.is_liked = False
post.likes.add(user)
return redirect('home')
home.html
{% if post.is_liked == True %}
<a href="javascript:{document.getElementById('like__post').submit()}"><button class="btn btn-primary btn-lg btn-block"><span class="oi oi-caret-top"></span> Like {{ post.total_likes }}</button></a>
{% else %}
<a href="javascript:{document.getElementById('like__post').submit()}"><button class="btn btn-primary btn-lg btn-block"><span class="oi oi-caret-top"></span> Unlike {{ post.total_likes }} </button></a>
{% endif %}
<form id="like__post" method="POST" action="{% url 'likepost' post.id %}">
{% csrf_token%}
<input type="hidden">
</form>