Like 按钮正在工作但没有更改为 Unlike in django

Like button is working but not changing to Unlike in django

一天以来,我一直在尝试与我的专家编码人员一起调试此问题,但我们无法在此处确定问题所在。 “赞”按钮工作正常,我可以查询总赞数,但“拍手”按钮不会变为“不喜欢”,我们不确定原因。我认为错误在于 html 行:

{% if liked and post.slug == blog_post.slug %} Unlike {% else %} Like {% endif %}

或 django 行:

context["liked"] = True if blog_post.likes.filter(id=request.user.id).exists() else False

非常感谢您能在此处找出问题所在!

views.py

def home_feed_view(request, *args, **kwargs):
    context = {}
    blog_posts = BlogPost.objects.all()
    context['blog_posts'] = blog_posts 
    if request.method=="POST":
        slug=request.POST["submit_slug"]
        blog_post = get_object_or_404(BlogPost, slug=slug)
        context['blog_post'] = blog_post
        context["liked"] = True if blog_post.likes.filter(id=request.user.id).exists() else False
        context['total_likes'] = blog_post.total_likes()
    type_of_post = TypeofPostFilter(request.GET, queryset=BlogPost.objects.all())
    context['type_of_post'] = type_of_post

    paginated_type_of_post = Paginator(type_of_post.qs, 13 )
    page = request.GET.get('page')
    post_page_obj = paginated_type_of_post.get_page(page)

    context['post_page_obj'] = post_page_obj

    return render(request, "HomeFeed/snippets/home.html", context)


def LikeView(request, slug):
    context = {}
    user = request.user
    if not user.is_authenticated:
        return redirect('must_authenticate')
    post = get_object_or_404(BlogPost, slug=slug)
    liked = False
    if post.likes.filter(id=request.user.id).exists():
        post.likes.remove(request.user)
        liked = False
    else:
        post.likes.add(request.user)
        liked = True
    return redirect(request.META.get('HTTP_REFERER', ''))
<td class="table-primary">
   <form action="{% url 'HomeFeed:like_post' post.slug %}" method="POST"> 
       {% csrf_token %} 
              
       <button type="submit" name="submit_slug" value="{{ post.slug }}" class='btn btn-primary btn-sm'>

       {% if liked and post.slug == blog_post.slug %} Unlike {% else %} Like 
       {% endif %}

       </button> 
       {{ post.total_likes }} Clap {{ post.total_likes|pluralize }}
         
   </form>
</td> 

urls.py

path('<slug>/like/', LikeView, name='like_post'),

models.py

class BlogPost(models.Model):
    chief_title = models.CharField(max_length=50, null=False, blank=False)
    body = models.TextField(max_length=5000, null=False, blank=False)
    likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='blog_posts', blank=True)
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    slug = models.SlugField(blank=True, unique=True)


好的,这里有一个更简单的方法来检查一个模型是否存在于另一个模型的 m2m 字段中:

html

{% if request.user in blog_post.likes.all %} Unlike {% else %} Like {% endif %}

查看

if request.user in blog_post.likes.all():

P.S. 在您的模型中,您应该将字段 likes 重命名为 likers 因为它与User 模型不是 Like 模型 :)

编辑

因此,要在单个页面上相应地轻松显示帖子列表及其喜欢的按钮,您需要在模板中执行此操作:

views.py

def posts(request): 
    blog_posts = BlogPost.objects.all()
    return render(request, 'index.html', {'blog_posts': blog_posts})

index.html

{% for post in blog_posts %}

    <h1>{{ post.chief_title }}</h1>
    <p>{{ post.author }} says: </p>
    <b>{{ post.body }}</b>
    <p> This post is liked by: </p>
    {% for user in post.likes %}
        <p>{{ user.username }}</p>
    {% endfor %}
    
    {% if request.user not in post.likes.all %} 
        <a href="{% url 'like_post' post.slug %}">Like</a>
    {% else %} 
        <a href="{% url 'like_post' post.slug %}">Unlike</a>
    {% endif %}

{% endfor %}