I have a models:
class Post(models.Model):
post_text = models.CharField(max_length=100, unique=True)
slug = models.SlugField(unique=True)
created_at = models.DateTimeField(auto_now_add=True)
class Comment(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author')
post_relation = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='comments')
comment_text = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
In my views I need get comments for posts in get_context_data:
class ResultsView(DetailView, FormMixin):
model = Post
template_name = 'posts.html'
form_class = CommentForm
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['comm'] = Comment.objects.filter(is_active=True)
return context
But in comm i get all comments in db.
In html:
{% for comment in question.comments.all %}
<div class="media mb-4">
<div class="media-body">
<h5 class="mt-0">{{ comment.author }}</h5>
{{ comment.comment_text }}
</div>
</div>
{% endfor %}
I try {% for comment in comm %}, try {% for comment in comm.all %} and always get all comments in db, not only comments in post.
Also I try fix this string in views: context['comm'] = Comment.objects.filter(is_active=True), but don't have a result.
The answer seems to be very simple, but I've already spent several hours trying and reading.