Django, how to display comments on a blog post in post template only for login user , i made these below mentioned models & views. Now my comments are successfully storing in database with name of user but the problem is its not shown on post . so far only count is displaying to see how many comments posted so far!
def get_comments(self):
return self.comments.all().order_by('-timestamp')
class Comment(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now_add=True)
commentfield = models.TextField()
post = models.ForeignKey(Blogpost, related_name='comments', on_delete=models.CASCADE)
def __str__(self):
return self.user.username
**My Forms**
from django import forms
from .models import Blogpost, Comment
class CommentForm(forms.ModelForm):
commentfield = forms.CharField(widget=forms.Textarea(attrs={
'class': 'form-control',
'placeholder': 'Type your comment',
'id': 'usercomment',
'rows': '4'
}))
class Meta:
model = Comment
fields = ("commentfield",)
**My Blog Post Views**
def blogpost(request, year, month, day, post):
category_count= get_category_count()
latest = Blogpost.objects.order_by('-publish')[0:4]
post = get_object_or_404(Blogpost, slug= post)
form = CommentForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
form.instance.user = request.user
form.instance.post = post
form.save()
return redirect('.')
context = {'post':post,
'latest': latest,
'category_count': category_count,
'form': form,
}
return render(request, 'blog/blogpost.html', context)
**My Templates**
<div class="post-comments">
<header>
<h3 class="h6">Post Comments<span class="no-of-comments">
({{ post.comments.count }})</span></h3>
</header>
{% for comment in post.get_comments %}
<div class="comment">
<div class="comment-header d-flex justify-content-between">
<div class="user d-flex align-items-center">
<div class="image">
{% if comment.user.author %}
<img src="{{ comment.user.author.profile_picture.url }}" alt="..."
class="img-fluid rounded-circle">
{% else %}
<img src="" alt="..."
class="img-fluid rounded-circle">
{% endif %}
</div>
<div class="title"><strong>{{ comment.user.username }}</strong><span
class="date">{{ comment.timestamp|timesince }} ago</span></div>
</div>
</div>```
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…