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

Django实现无未激活评论用户发新评论的报错排查

报错原因与解决方案

一、报错根源

你使用Comment.objects.get(active=False, profile=profile)查询用户未激活评论时,get()方法要求必须返回恰好一条匹配记录。如果当前用户没有未激活评论,Django就会抛出Comment matching query does not exist.异常,这就是报错的直接原因。

二、修复方案

1. 视图层逻辑修正

替换get()为filter().exists()(返回布尔值,无匹配时不会报错),同时添加“禁止有未激活评论的用户提交新评论”的验证逻辑:

修改后的视图代码:

from django.shortcuts import get_object_or_404, render, HttpResponseRedirect
from django.db.models import Count
from .models import Post, Comment, Profile, Tag
from .forms import CommentForm

def post_detail(request, year, month, day, slug):
    post = get_object_or_404(Post, slug=slug, status='published', publish__year=year, publish__month=month, publish__day=day)
    tags = Tag.objects.all()
    tagsList = [tag.name for tag in post.tags.get_queryset()]  # 简化列表生成
    
    has_inactive_comments = False
    if request.user.is_authenticated:
        profile = Profile.objects.get(user=request.user)
        # 用exists()判断是否存在未激活评论,避免无匹配时报错
        has_inactive_comments = Comment.objects.filter(active=False, profile=profile).exists()
    
    comments = post.comments.filter(active=True)
    new_comment = None
    comment_form = CommentForm()
    
    if request.method == 'POST':
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():
            # 验证用户是否有未激活评论,有则拒绝提交
            if has_inactive_comments:
                # 给表单添加全局错误提示
                comment_form.add_error(None, '您已有待审核的评论,请等待审核通过后再提交新评论')
            else:
                new_comment = comment_form.save(commit=False)
                new_comment.profile = profile
                new_comment.post = post
                new_comment.save()
                return HttpResponseRedirect(request.path_info)
        
    post_tags_ids = post.tags.values_list('id', flat=True)
    similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id)
    similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags', '-publish')[:3]
        
    context = {
        'post': post,
        'comments': comments,
        'new_comment': new_comment,
        'comment_form': comment_form,
        'similar_posts': similar_posts,
        'tagsList': tagsList,
        'tags': tags,
        'has_inactive_comments': has_inactive_comments
    }
    return render(request, 'blog/post/detail.html', context)

2. 模板层调整

将模板中判断inactive_comments的逻辑改为has_inactive_comments,同时添加表单错误提示:

修改后的模板代码:

{% if request.user.is_authenticated %}
<div class="new_comment">
    {% if has_inactive_comments %}
        <h4>نظر شما با موفقیت ثبت شد و در حال بررسی است.</h4>
    {% else %}     
        <h4>نظر خود را اضافه کنید</h4></br>
        <form method="post">                               
            <div class="row" dir="rtl">
                <div class="col-sm-12 col-md-8">
                    {{ comment_form.body|attr:"class:form-control"|attr:"type:text" }}
                </div>
            </div>
            {% csrf_token %} 
            <!-- 显示表单全局错误提示 -->
            {% if comment_form.non_field_errors %}
                <div class="alert alert-danger">
                    {{ comment_form.non_field_errors.as_text }}
                </div>
            {% endif %}
            <div class="row"><br/>
                <div class="col-sm-12 col-md-8"> 
                    <input type="submit" value="ارسال نظر" class="btn send btn-primary" href="#"/> 
                </div>
            </div>                                  
        </form>          
    {% endif %}
</div>
{% else %}
<p>برای انتشار دیدگاه خود <a href="{% url 'account:login' %}">وارد پروفایل کاربری</a> خود شوید یا در سایت <a href="{% url 'account:register' %}">ثبت نام</a> کنید.</p>
{% endif %}

三、关键说明

  • filter().exists():高效判断是否存在匹配记录,返回布尔值,无匹配时不会抛出异常,完美适配“用户可能没有未激活评论”的场景。
  • POST请求时的验证:确保即使用户绕过前端限制,后端也能拦截有未激活评论的用户提交新评论,保证业务逻辑的安全性。
  • 表单错误提示:给用户明确的操作反馈,提升体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 07:15:56