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

如何在Django中为指定模型添加评论?Polls应用评论功能实现需求

在Django Polls应用中为Question添加评论功能

嘿,我来帮你搞定给Question模型加评论的需求!咱们一步步来,从模型定义到模板展示全流程覆盖:

1. 更新models.py,添加Comment模型

首先在polls的models.py里新增Comment类,关联到Question模型,同时保存评论的必要信息(比如评论内容、评论者、创建时间):

from django.db import models
from django.utils import timezone

class Question(models.Model):
    # 你原有的Question字段,比如:
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

class Choice(models.Model):
    # 你原有的Choice字段,比如:
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

# 新增的Comment模型
class Comment(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='comments')
    name = models.CharField(max_length=80)
    email = models.EmailField(blank=True)  # 可选,允许匿名评论的话可以设为null=True
    content = models.TextField()
    created_at = models.DateTimeField(default=timezone.now)

    class Meta:
        ordering = ['-created_at']  # 最新的评论排在前面

    def __str__(self):
        return f'Comment by {self.name} on {self.question.question_text}'

2. 在admin.py中注册Comment模型

这样你就能在Django后台管理评论了,打开polls/admin.py:

from django.contrib import admin
from .models import Question, Choice, Comment

admin.site.register(Question)
admin.site.register(Choice)
admin.site.register(Comment)  # 注册Comment模型

3. 创建评论表单(forms.py)

如果polls目录下没有forms.py,新建一个,用ModelForm快速生成评论表单:

from django import forms
from .models import Comment

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ['name', 'email', 'content']  # 只展示需要用户填写的字段
        # 可以给字段加自定义标签或样式,比如:
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control'}),
            'email': forms.EmailInput(attrs={'class': 'form-control'}),
            'content': forms.Textarea(attrs={'class': 'form-control', 'rows': 3}),
        }

4. 修改视图函数处理评论提交与展示

接下来要修改polls/views.py里的两个视图:详情页(处理评论提交)和结果页(展示评论)。

处理评论提交(detail视图)

找到你的detail视图,修改它来处理POST请求(用户提交评论):

from django.shortcuts import get_object_or_404, render, redirect
from django.urls import reverse
from .models import Question, Comment
from .forms import CommentForm

def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    comment_form = CommentForm()

    if request.method == 'POST':
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            comment = comment_form.save(commit=False)
            comment.question = question
            comment.save()
            # 提交后重定向到当前详情页,避免重复提交
            return redirect('polls:detail', question_id=question.id)

    context = {
        'question': question,
        'comment_form': comment_form,
    }
    return render(request, 'polls/detail.html', context)

展示评论(results视图)

修改results视图,把当前Question的所有评论查出来传给模板:

def results(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    # 通过related_name='comments'获取该问题的所有评论
    comments = question.comments.all()
    context = {
        'question': question,
        'comments': comments,
    }
    return render(request, 'polls/results.html', context)

5. 更新模板文件

在details.html中添加评论表单

打开polls/templates/polls/detail.html,在合适的位置(比如投票选项下方)添加评论提交表单:

<h3>留下你的评论</h3>
<form method="post">
    {% csrf_token %}
    {{ comment_form.as_p }}
    <button type="submit" class="btn btn-primary">提交评论</button>
</form>

在results.html中展示评论

打开polls/templates/polls/results.html,在结果展示区域下方添加评论列表:

{% if comments %}
    <h3>用户评论</h3>
    <div class="comments-list">
        {% for comment in comments %}
            <div class="comment-item mb-3">
                <strong>{{ comment.name }}</strong>
                {% if comment.email %}<small class="text-muted">({{ comment.email }})</small>{% endif %}
                <p class="text-muted">{{ comment.created_at|date:"Y-m-d H:i" }}</p>
                <p>{{ comment.content }}</p>
                <hr>
            </div>
        {% endfor %}
    </div>
{% else %}
    <p>还没有评论,快来抢沙发吧!</p>
{% endif %}

最后一步:迁移数据库

别忘了执行数据库迁移,让新的Comment模型生效:

python manage.py makemigrations
python manage.py migrate

这样就完成啦!用户现在可以在详情页提交评论,在结果页看到所有相关评论了~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:08:53