You need to enable JavaScript to run this app. Django点赞功能触发IntegrityError NOT NULL约束失败及跳转问题
优惠活动
大模型
产品
解决方案
定价
更多

Django点赞功能触发IntegrityError NOT NULL约束失败及跳转问题

现有代码核心问题梳理

  1. 点赞视图处理完逻辑后直接渲染单页模板,未传递模板需要的single_post、count_like等上下文参数,也没有匹配post_detail路由要求的category_slug参数,是你截图报错的核心原因
  2. 没有统计点赞数的逻辑,模板中count_like变量无值
  3. 采用表单同步提交的方式,没有做锚点定位或无刷新处理,提交后会默认回到页面顶部

修复步骤

1. 调整Post模型,新增点赞数计算属性

不用把点赞数写入Post表字段,避免数据同步问题,直接通过关联查询动态计算即可,在你的Post模型中新增代码:

class Post(models.Model):
    # 你原来的其他字段保留
    category = models.ForeignKey(Category, on_delete=models.CASCADE) # 确保你有这个分类外键,字段名不对就换成你自己的

    # 新增点赞数属性
    @property
    def count_like(self):
        return self.postlike_set.count()

2. 修复点赞视图逻辑

两种方案可选,对应不同的页面停留需求:

方案A:锚点跳转方案(改动最小,不用写JS)

修改views.py中的like_or_dislike_post函数:

from django.shortcuts import get_object_or_404, redirect, reverse

def like_or_dislike_post(request, post_slug):
    if request.method == 'POST':
        each_post = get_object_or_404(Post, slug=post_slug)
        # 处理点赞/取消逻辑
        liked_post = PostLike.objects.filter(user = request.user, post = each_post).first()
        if liked_post:
            liked_post.delete()
        else:
            PostLike.objects.create(user=request.user, post=each_post)
        
        # 重定向回详情页,携带分类slug参数,加锚点跳到点赞区域
        category_slug = each_post.category.slug
        return redirect(reverse('post_detail', args=[category_slug, post_slug]) + '#like-section')

对应修改HTML代码,给点赞区域加锚点ID:

<!-- 新增id为like-section的外层容器作为锚点 -->
<div id="like-section">
<a href="#" onclick="document.getElementById('likebutton').submit()" >
     <div class="ui labeled button" tabindex="0">
          <div class="ui red button comment">
              <i class="heart icon"></i> Like
          </div>
         <a class="ui basic red left pointing label"> {{ single_post.count_like | intcomma}} </a>
    </div>
 </a>

<form id="likebutton" action="{% url 'like_or_dislike_post' single_post.slug %}" method="POST">
       {% csrf_token %}
</form>
</div>
方案B:AJAX无刷新方案(体验最好,完全不跳转页面)

修改views.py中的like_or_dislike_post函数,返回JSON数据:

from django.shortcuts import get_object_or_404
from django.http import JsonResponse

def like_or_dislike_post(request, post_slug):
    if request.method == 'POST':
        each_post = get_object_or_404(Post, slug=post_slug)
        liked_post = PostLike.objects.filter(user = request.user, post = each_post).first()
        is_liked = False
        if liked_post:
            liked_post.delete()
        else:
            PostLike.objects.create(user=request.user, post=each_post)
            is_liked = True
        # 返回点赞状态和最新点赞数
        return JsonResponse({
            'count_like': each_post.count_like,
            'is_liked': is_liked
        })

对应替换HTML代码,去掉表单,用AJAX提交:

<div id="like-section">
     <div class="ui labeled button like-btn" tabindex="0" data-slug="{{ single_post.slug }}" data-csrf="{{ csrf_token }}">
          <div class="ui red button comment">
              <i class="heart icon"></i> 
              <span class="like-text">{% if request.user in single_post.postlike_set.all.values_list('user', flat=True) %}取消{% endif %}点赞</span>
          </div>
         <a class="ui basic red left pointing label like-count"> {{ single_post.count_like | intcomma}} </a>
    </div>
</div>

<script>
document.querySelector('.like-btn').addEventListener('click', function() {
    const slug = this.dataset.slug;
    const csrf = this.dataset.csrf;
    fetch(`/like_post/${slug}`, {
        method: 'POST',
        headers: {
            'X-CSRFToken': csrf,
        },
    }).then(res => res.json())
    .then(data => {
        // 局部更新页面内容,完全不刷新页面
        document.querySelector('.like-count').textContent = data.count_like;
        document.querySelector('.like-text').textContent = data.is_liked ? '取消点赞' : '点赞';
    })
})
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 07:06:04