Comments are registered on the desired page, and for people who aren’t logged in, if they want to leave a comment, it says to enter the site first, but later the comments are registered under the name AnonymousUser. I don’t want this registration to happen.
Which part and how should be edited?
in 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)
in 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 %}
`
Thanks in advance for your help
2
Answers
Your
if user.is_authenticated
is only in the template, so you’re only deciding whether to show the comments to users based on their authentication status.In your django views there is always a user associated with the request. If they’re not logged in it’s just an anonymous user.
You have a couple of options:
It seems like you’re allowing comments to be posted by users who are not logged in, but you want to prevent these comments from being attributed to an "AnonymousUser." To achieve this, you should check whether the user is authenticated before attempting to create a comment with their username.
Here’s an updated version of what your
views.py
should look like:In this version, the
@login_required
decorator is used to ensure that only authenticated users can access theproduct_detail
view. If a user is not authenticated, they will be redirected to the login page (TheLOGIN_URL
in yoursettings.py
).This way, if a user is not logged in and tries to post a comment, they will be prompted to log in first, and the comment won’t be saved as an "AnonymousUser."