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

如何在Django帖子详情页内添加评论表单及报错解决

在Django视频详情页内实现评论表单(解决TypeError问题)

错误原因

你遇到的TypeError是因为创建Comment对象时,post_id=play传入了整个Video对象,而post_id字段需要的是Video对象的ID数值,导致类型不匹配。

修正方案

1. 修正视图函数

调整评论创建逻辑,直接使用外键字段post关联Video对象,同时优化重定向和评论查询逻辑:

def play_video(request, slug):
    play = get_object_or_404(Video, slug=slug)
    # 获取当前视频的所有评论,按时间倒序排列
    comments = play.comment_set.all().order_by('-id')
    
    if request.method == 'POST':
        comments_content = request.POST.get('comments')
        # 检查评论内容不为空
        if comments_content.strip():
            Comment.objects.create(
                user=request.user,
                comments=comments_content,
                post=play
            )
        # 重定向回当前视频详情页,保持用户体验连贯
        return redirect('play_video', slug=slug)
    
    context = {
        'play': play,
        'comments': comments
    }
    return render(request, 'video/play_video.html', context)

2. 优化模板(添加评论展示)

在详情页中同时展示评论表单和已有评论,完善页面功能:

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
    rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
    crossorigin="anonymous">

<div class="container">
    <!-- 视频展示区域 -->
    <div class="row mb-4">
        <div class="col-md-9">
            <h2>{{ play.title }}</h2>
            <video controls class="w-100">
                <source src="{{ play.video.url }}" type="video/mp4">
                你的浏览器不支持视频播放
            </video>
        </div>
    </div>

    <!-- 评论提交表单 -->
    <div class="row mb-4">
        <div class="col-md-9">
            <form action="" method="post">
                {% csrf_token %}
                <div class="input-group">
                    <textarea name="comments" id="comment" rows="3"
                    class="form-control" placeholder="写下你的评论"></textarea>
                    <button class="btn btn-primary" type="submit">提交</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 已有评论列表 -->
    <div class="row">
        <div class="col-md-9">
            <h3>评论</h3>
            {% for comment in comments %}
            <div class="card mb-2">
                <div class="card-body">
                    <h5 class="card-title">{{ comment.user.username }}</h5>
                    <p class="card-text">{{ comment.comments }}</p>
                    <p class="card-text"><small class="text-muted">{{ comment.created_on }}</small></p>
                </div>
            </div>
            {% empty %}
            <p>暂无评论,快来抢沙发吧!</p>
            {% endfor %}
        </div>
    </div>
</div>

3. 优化评论模型

给Comment模型添加评论时间字段,并修正__str__方法:

class Comment(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    comments = models.TextField(max_length=200)
    post = models.ForeignKey(Video, on_delete=models.CASCADE)
    created_on = models.DateTimeField(auto_now_add=True)  # 新增评论时间字段

    def __str__(self):
        return f"{self.user.username}: {self.comments[:20]}"  # 避免返回用户对象导致错误

关键说明

  • 外键关联:创建Comment时直接使用post=play,Django会自动处理外键ID的关联,比手动传入post_id=play.id更直观。
  • 用户体验:提交评论后重定向回当前详情页,而不是列表页,让用户能立即看到自己的评论。
  • 表单验证:添加评论内容非空检查,避免创建无意义的空评论。
  • 评论展示:通过play.comment_set.all()反向查询当前视频的所有评论,按时间倒序排列展示。

内容的提问来源于stack exchange,提问作者Adamu Abdulkarim Dee

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 01:07:51