如何使用 Django 框架显示帖子的详细信息及其评论?

问题描述

Django 框架的新手,对编码有点生疏。我目前正在尝试从头开始构建一个技术博客,并一直使用 Django Central 教程作为指导。目前,我被困在 this tutorial 上,特别是让我的观点同时显示帖子的详细信息和评论表单。

在教程中,作者从基于类的视图切换到使用 get_object_or_404()函数来检索帖子。我能够在没有任何错误消息的情况下切换到此功能,但帖子详细信息返回空白。返回到基于类的视图可以解决这个问题,但我想使用教程中提供的功能

代码如下:

views.py

def post_detail(request,slug):
template_name = 'post_detail.html'
post = get_object_or_404(Post,slug=slug)
comments = post.comments.filter(active=True)
new_comment = None
# Comment posted
if request.method == 'POST':
    comment_form = CommentForm(data=request.POST)
    if comment_form.is_valid():

        # Create Comment object but don't save to database yet
        new_comment = comment_form.save(commit=False)
        # Assign the current post to the comment
        new_comment.post = post
        # Save the comment to the database
        new_comment.save()
else:
    comment_form = CommentForm()

return render(request,template_name,{'post': post,'comments': comments,'new_comment': new_comment,'comment_form': comment_form})

这是使用此功能的帖子详细信息的屏幕截图:

Screenshot of blog

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)