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

未登录用户评论被注册为AnonymousUser的问题及修改方案咨询

问题解决方法

1. 后端代码修改(views.py)

当前后端未校验用户登录状态,直接保存了评论请求。需要在处理评论提交的逻辑前,增加用户登录判断:

修改后的views.py代码:

from django.contrib import messages  # 如需添加提示消息需导入

comments = Comment.objects.filter(product=product)

if request.method == 'POST':
    # 处理评论提交
    if 'comment' in request.POST:
        # 新增:判断用户是否已登录
        if request.user.is_authenticated:
            author = request.user
            content = request.POST.get('content')
            comment = Comment(product=product, author=author, content=content)
            comment.save()
        else:
            # 可选:添加提示消息,告知用户需登录才能评论
            messages.error(request, "请先登录再提交评论")

context = {
    'comments': comments, 
}

return render(request, 'auctions/product_detail.html', context)

2. 前端代码优化(product_detail.html)

当前前端仅控制了评论列表的显示,未限制评论提交表单的访问(假设你存在评论提交表单)。需要将评论提交表单也放在登录判断范围内,避免未登录用户看到提交入口:

修改后的product_detail.html代码(示例包含提交表单):

<h3 id="h3">Comments</h3>

{% if user.is_authenticated %}
    <ul>
        {% for comment in comments %}
            <li><a>{{ comment.author }} : {{comment.content}}</a></li>
        {% endfor %}
    </ul>   
    <!-- 评论提交表单 -->
    <form method="POST">
        {% csrf_token %}
        <textarea name="content" placeholder="写下你的评论..."></textarea>
        <button type="submit" name="comment">提交评论</button>
    </form>
{% else %}
   未登录,请先登录才能评论。
{% endif %}

关键说明

  • 后端校验是核心:即便前端隐藏了提交入口,恶意用户仍可通过直接发送POST请求提交评论,所以后端必须做登录状态校验,确保仅登录用户能保存评论。
  • 前端优化是补充:让未登录用户看不到提交表单,减少无效操作,提升体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 14:42:53