You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django点赞数不显示、点击仅刷新页面问题求助

嘿,我来帮你一步步解决这些问题,咱们从最明显的问题开始排查:

1. 先搞定点赞总数不显示的问题

看你的模板代码,循环遍历的是post in post_list,但你在点赞按钮里用了{{ obj.likes.count }}——这里的obj是未定义的变量,应该换成当前循环的post才对!

修改模板里的点赞按钮代码,把所有obj替换成post:

<p><a class='like-btn' data-href='{{ post.get_api_like_url }}' data-likes='{{ post.likes.count }}' href='{{ post.get_like_url }}'> {{ post.likes.count }} Agree</a></p>

这样页面就能正确渲染出当前帖子的点赞数了。

2. 点击点赞后跳转到post_detail页面

你的PostLikeToggle视图现在返回的是obj.get_absolute_url(),首先得确保Post模型里的get_absolute_url方法指向的是帖子详情页。如果还没定义这个方法,先在models.py的Post类里加上:

def get_absolute_url(self):
    # 注意这里的url名称要和你urls.py里post_detail的name一致,比如如果是命名空间的话要写成"posts:post_detail"
    return reverse("post_detail", kwargs={"pk": self.pk})

如果已经定义了但跳转不对,或者想直接在视图里指定跳转目标,也可以修改PostLikeToggle的get_redirect_url方法:

class PostLikeToggle(RedirectView):
    def get_redirect_url(self, *args, **kwargs):
        slug = self.kwargs.get("slug")
        obj = get_object_or_404(Post, slug=slug)
        # 直接返回post_detail的URL
        return reverse("post_detail", kwargs={"pk": obj.pk})
        
        # 下面的点赞逻辑保持不变
        user = self.request.user
        if user.is_authenticated():
            if user in obj.likes.all():
                obj.likes.remove(user)
            else:
                obj.likes.add(user)

3. 实现无刷新点赞(避免页面刷新)

现在点击按钮会刷新页面,是因为a标签默认会触发跳转行为。你已经写好了PostLikeAPIToggle接口,咱们用JavaScript来异步请求接口,更新点赞数后再跳转详情页:

在模板的{% endblock %}之前加上这段JS代码:

<script>
document.addEventListener('DOMContentLoaded', function() {
    const likeButtons = document.querySelectorAll('.like-btn');
    
    likeButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault(); // 阻止默认页面跳转
            
            const apiUrl = this.getAttribute('data-href');
            // 从点赞按钮的href里提取帖子详情页的URL(把/like/后缀去掉)
            const postDetailUrl = this.getAttribute('href').replace('/like/', '');
            
            // 发送异步请求
            fetch(apiUrl, {
                method: 'GET',
                credentials: 'include', // 带上session信息确保登录状态
                headers: {
                    'X-CSRFToken': getCookie('csrftoken') // 必须带上CSRF Token
                }
            })
            .then(response => response.json())
            .then(data => {
                // 更新页面上的点赞数
                let currentLikes = parseInt(this.getAttribute('data-likes'));
                if (data.liked) {
                    currentLikes += 1;
                    this.textContent = `${currentLikes} Agree`;
                } else {
                    currentLikes -= 1;
                    this.textContent = `${currentLikes} Agree`;
                }
                this.setAttribute('data-likes', currentLikes);
                
                // 跳转到帖子详情页
                window.location.href = postDetailUrl;
            })
            .catch(error => console.error('点赞出错:', error));
        });
    });
    
    // 辅助函数:获取Cookie里的CSRF Token
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
});
</script>

这样点击按钮后,会先异步更新点赞状态和页面上的点赞数,然后再跳转到详情页,不会出现整页刷新的情况。

额外提醒:别忘了给未登录用户做个判断,避免他们点击按钮时出错,模板里可以加个判断:

{% if user.is_authenticated %}
<p><a class='like-btn' data-href='{{ post.get_api_like_url }}' data-likes='{{ post.likes.count }}' href='{{ post.get_like_url }}'> {{ post.likes.count }} Agree</a></p>
{% else %}
<p>{{ post.likes.count }} Agree (请登录后点赞)</p>
{% endif %}

内容的提问来源于stack exchange,提问作者user2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:24:03