未登录无法注册评论

问题描述 投票:0回答:1

评论被注册在想要的页面上,对于没有登录的人来说,如果他们想发表评论,它会说先进入网站,但稍后评论会以AnonymousUser的名义注册。我不希望发生这种注册。 应该编辑哪一部分以及如何编辑?

在views.py中:

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

if request.method == 'POST':

    # comment

    if 'comment' in request.POST:
        author = request.user
        content = request.POST.get('content')
        comment = Comment(product=product, author=author, content=content)
        comment.save()


context = {
        'comments': comments, 
        }



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

在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>   
    {% else %}
       Not signed in.
    {% endif %}

`

提前感谢您的帮助

python html django authentication comments
1个回答
0
投票

您的

if user.is_authenticated
仅在模板中,因此您只需根据用户的身份验证状态决定是否向用户显示评论。

在您的 django 视图中始终有一个与请求关联的用户。如果他们没有登录,那么它只是一个匿名用户。

您有几个选择:

  1. 您对视图进行身份验证检查,以便只有登录的用户才能访问该视图。
  2. 您在视图发布时检查用户的身份验证状态(您根本没有这样做 - 这是您检查它是否是 POST 的地方),如果他们未登录,则验证失败并且不会发生任何更改(即新评论)已提交。您还可以设置某种失败消息,以便用户知道他们必须登录才能发表评论。
© www.soinside.com 2019 - 2024. All rights reserved.