html代码中的if statement
不能正常工作,所有的点赞都通过点赞按钮发送,但是按钮的文字没有改变。我尝试了不同的方式来传递上下文,但是没有一个起作用。
无论喜欢与否,该按钮均显示为like
,并且在帖子列表视图中也是如此。
views.py:
from django.shortcuts import render,get_object_or_404
from django.views.generic import ListView
from .models import Blog
from django.http import HttpResponseRedirect
class BlogsList(ListView):
model=Blog
template_name='blog/home.html'
context_object_name='blogs'
ordering=['-date_posted']
def like_post(request, blog_id):
post = get_object_or_404(Blog, id=blog_id)
is_liked=False
if post.likes.filter(id=request.user.id).exists():
post.likes.remove(request.user)
is_liked=False
else:
post.likes.add(request.user)
is_liked=True
context={
'is_liked':is_liked
}
return HttpResponseRedirect(Blog.get_absolute_url(blog_id))
def post_detail(request, id):
post=get_object_or_404(Blog, id=id)
context={
'post':post,}
return render(request, 'blog/post_detail.html',context)
def check_liked(request):
post = get_object_or_404(Blog, id=blog_id)
is_liked=False
if post.likes.filter(id=request.User.id).exists():
is_liked=True
else:
is_liked=False
context={
'is_liked':is_liked
}
return render(request, 'blog/post_detail.html',context)
models.py :
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class Blog(models.Model):
title=models.CharField(max_length=100)
content=models.TextField()
date_posted=models.DateTimeField(default=timezone.now)
author=models.ForeignKey(User, on_delete=models.CASCADE)
likes=models.ManyToManyField(User,related_name='likes',blank=True)
def __str__(self):
return self.title
def get_absolute_url(blog_id):
return reverse('post-detail',args=[str(blog_id)])
urls.py :
from django.urls import path
from . import views
urlpatterns=[
path('',views.BlogsList.as_view(),name='blog-home'),
path('<int:blog_id>/like/', views.like_post, name='like_post'),
path('post/<int:id>/', views.post_detail, name='post-detail'),
]
post_detail.html :
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}">
<div class="media-body">
<div class="article-metadata">
<h2>{{ post.author }}</h2>
<small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small>
</div>
<h2>{{ post.title }}</h2>
<p class="article-content">{{ post.content }}</p>
</div>
<div>
<form action="{% url 'like_post' post.id %}">
{% csrf_token %}
{% if is_liked %}
<button type='submit' name='blog_id' value="{{ post.id }}" class="btn btn-danger">Unlike</button>
{% else %}
<button type='submit' name='blog_id' value="{{ post.id }}" class="btn btn-primary">Like</button>
{% endif %}
</form>
</div>
</article>
答案 0 :(得分:0)
您还需要在帖子详细信息处传递is_liked
。
def post_detail(request, id):
post = get_object_or_404(Blog, id=id)
context = {
'post': post,
'is_liked': post.likes.filter(id=request.user.id).exists()
}
return render(request, 'blog/post_detail.html', context)