简体   繁体   中英

Django: get_context_data for comments related post

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.

You can filter with:

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, 
        )

and then render with:

{% 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM