Django: get_context_data для комментариев связанный пост

У меня есть 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)

В моем views мне нужно получить comments для posts в 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

Но в comm я получаю все комментарии в базе данных.

В 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 %}

Я пробую {% for comment in comm %}, пробую {% for comment in comm.all %} и всегда получаю все комментарии в db, а не только комментарии в посте.

Также я пытаюсь исправить эту строку в views: context['comm'] = Comment.objects.filter(is_active=True), но не имею результата.

Ответ кажется очень простым, но я уже потратил несколько часов на попытки и чтение. Любая помощь приветствуется.

Вы можете фильтровать с помощью:

class ResultsView(FormMixin, DetailView):
    model = Post
    template_name = 'posts.html'
    form_class = CommentForm

    def get_context_data(self, **kwargs):
        return super().get_context_data(
            **kwargs, comms=self.object.comments.filter(is_active=True)
        )

и затем визуализировать с помощью:

{% for comment in comms %}
    # …
{% endfor %}

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.


Note: The related_name=… parameter [Django-doc] is the name of the relation in reverse, so from the User model to the Comment model in this case. Therefore it (often) makes not much sense to name it the same as the forward relation. You thus might want to consider renaming the author relation to comments.

Вернуться на верх