I am building a discussion Forum where user can ask question and can reply on other's questions. I want to show "Answered" if the Question is already answered and show "Not answered yet" if Question is not answered by any user
My model.py
class Post(models.Model):
user1 = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
post_id = models.AutoField
post_content = models.CharField(max_length=5000)
timestamp= models.DateTimeField(default=now)
image = models.ImageField(upload_to="images",default="")
def __str__(self):
return f'{self.user1} Post'
class Replie(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
reply_id = models.AutoField
reply_content = models.CharField(max_length=5000)
post = models.ForeignKey(Post, on_delete=models.CASCADE, default='')
timestamp= models.DateTimeField(default=now)
image = models.ImageField(upload_to="images",default="")
def __str__(self):
return f'{self.user1} Post'
View.py
def forum(request):
user = request.user
profile = Profile.objects.all()
if request.method=="POST":
user = request.user
image = request.user.profile.image
content = request.POST.get('content','')
post = Post(user1=user, post_content=content, image=image)
post.save()
messages.success(request, f'Your Question has been posted successfully!!')
return redirect('/forum')
posts = Post.objects.filter().order_by('-timestamp')
return render(request, "forum.html", {'posts':posts})
def discussion(request, myid):
post = Post.objects.filter(id=myid).first()
replies = Replie.objects.filter(post=post)
if request.method=="POST":
user = request.user
image = request.user.profile.image
desc = request.POST.get('desc','')
post_id =request.POST.get('post_id','')
reply = Replie(user = user, reply_content = desc, post=post, image=image)
reply.save()
messages.success(request, f'Your Reply has been posted successfully!!')
return redirect('/forum')
return render(request, "discussion.html", {'post':post, 'replies':replies})
in my forum.html I want to show those messages.
CodePudding user response:
You can access how many replies a post has in your template with post.replie_set.count
(assuming that you are looping over the posts with {% for post in posts %}
. With this into account you can display the info that you want inside an if
statement block in your forum.html
file:
...
{% for post in posts %}
...
{% if post.replie_set.count > 0 %}
<p>Answered</p>
{% else %}
<p>Not answered yet</p>
{% endif %}
...
{% endfor %}
...
This way we're checking if a post has more than 0 replies (that's to say, it has been replied to). Otherwise it has no replies so we display that it's not answered.