首页 > 解决方案 > 如何在特定帖子中显示评论

问题描述

如何在 Django 中显示对特定帖子的评论。我看过很多教程,我可以理解评论可以通过 ForeignKey 显示到 Post 使用related_name 和 id 传递通过 url。我一直被这个问题困扰,如果有人能帮我解决这个问题,我会很高兴,我想在不向模型添加相关名称的情况下显示对每个特定帖子的评论。

class Post(models.Model):
    poster_profile = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, blank=True,null=True)

class Comments (models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, blank=True,null=True)
    commented_image = models.ForeignKey(Post, on_delete=models.CASCADE, null=True, blank=True) #i don't want a related_name
    comment_post = models.TextField()

def home_view(request):
    all_comments = Comments.objects.filter(user=request.user, active=True)
    posts = Comments.objects.filter(pk__in=all_comments)
context = {'posts': posts}
return render(request,'home.html', context)

#this displays all comments for all post, how do i assign comments to the particular post commented on
{% for comment in posts %}
<p>{{ comment.comment_post }}</p>
{% endfor %}

标签: pythondjango

解决方案


commented_image您可以使用以下方法过滤(ForeignKey对于Post模型而言)的主键:

def comments_on_post(request, post_pk):
    all_comments = Comments.objects.filter(
        user=request.user,
        active=True,
        commented_image_id=post_pk
    )
    context = {'posts': all_comments }
    return render(request,'home.html', context)

当然这意味着在 URL 中你应该对Post. 所以urls.py有一个urlpatterns列表:

# app/urls.py

from app import views

urlpatterns = [
    # …,
    path('comments/<int:post_pk>', views.comments_on_post)
]

因此,您可以通过访问comments/14例如获取Postwith的评论来触发视图pk=14(当然,假设存在)。


推荐阅读