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
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:
Where you need to be doing this is in your view code:
if 'comment' in request.POST:
author = request.user
if author.is_authenticated:
content = request.POST.get('content')
comment = Comment(product=product, author=author, content=content)
comment.save()
Currently this saves comments regardless of who has added them. You have the request.user
here, so you need to check the is_authenticated
value before you do the save - just don't save if they are not authenticated (I also suggest you use the messages framework to inform the user their comment wasn't saved because they need to log in, but that's extra and entirely up to you).