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

如何扩展Django类视图(Class Based View)修复评论表单不生效问题

代码调整方案

一、views.py 修正

原代码问题:

  • 自定义的comments方法不是Django类视图的内置回调方法,不会被自动调用
  • 方法内没有获取当前Post对象的逻辑,post变量未定义
  • save(committ=False)拼写错误,应为commit=False
  • 渲染模板错误,应该渲染详情页模板而非allblogs.html

修正后代码:

from django.shortcuts import render
from django.views.generic import DetailView
from .models import Post
from .forms import CommentForm

class PostDetailView(DetailView):
    model = Post
    template_name = 'blogdetail.html'
    pk_url_kwarg = 'id'

    # 重写get_context_data给模板传递评论表单和已有评论
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['comments'] = self.object.comments.all()
        context['comment_form'] = CommentForm()
        return context

    # 重写post方法处理表单提交
    def post(self, request, *args, **kwargs):
        self.object = self.get_object() # 获取当前帖子对象
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():
            new_comment = comment_form.save(commit=False)
            new_comment.post = self.object # 手动绑定评论对应的帖子
            new_comment.save()
        # 提交后重新渲染详情页
        context = self.get_context_data()
        context['comment_form'] = comment_form # 验证失败时保留错误信息
        return render(request, self.template_name, context)

二、forms.py 修正

原代码问题:不需要在表单字段中暴露post字段,避免用户手动选择帖子,由视图侧自动绑定即可
修正后代码:

from django import forms
from .models import Comment

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ['body'] # 仅保留评论内容字段

三、blogdetail.html 修正

原代码问题:

  • form标签未指定method="POST",默认是GET请求不会触发视图的post方法
  • 作者跳转a标签无内容显示
    修正后代码:
{% extends 'base.html' %}

{% block content %}
<h1>{{post.title}}</h1>
<p>{{post.created_on}}</p>
<p><a href="{% url 'userpage' post.author.username %}">{{post.author}}</a>:{{post.author}}</p>
<p>{{post.text}}</p>
<!-- 新增method属性 -->
<form method="POST">
{{comment_form.as_p}}
<p><input type="submit" value="add"></p>
{% csrf_token %}
</form>

<!-- 可选新增已有评论展示逻辑 -->
<h3>评论列表</h3>
{% for comment in comments %}
<div>
    <p>{{comment.body}}</p>
    <small>发布时间:{{comment.created_on}}</small>
</div>
{% empty %}
<p>暂无评论</p>
{% endfor %}

{% endblock content %}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 06:54:03