python - 如何在特定帖子中显示评论
问题描述
如何在 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 %}
解决方案
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
例如获取Post
with的评论来触发视图pk=14
(当然,假设存在)。
推荐阅读
- javascript - Gulp.src 匹配带方括号的文件夹
- python-3.x - 在无限循环中读取 ipywidgets 滑块值
- typescript - TypeORM - 在侦听器方法中使用事务 (BeforeUpdate)
- video - 哪种视频格式适合平面图形动画
- python - 烧瓶中的jinja2.exceptions.TemplateSyntaxError
- azure-machine-learning-studio - Azure ML:- 每次调用 Azure ML Web 服务时,如何使用来自第三方系统的数据重新训练 Azure ML 模型
- c# - 坚持单元测试数组中的最大数量
- c++ - 在方法中使用未初始化的变量
- r - 基于字符串中位置的条件字符串匹配 (r)
- node.js - 在不同服务器或同一服务器上托管服务器和客户端应用程序?