【问题标题】:How can I display my comment form on the post detail page Django如何在帖子详细信息页面 Django 上显示我的评论表单
【发布时间】:2020-01-25 20:31:42
【问题描述】:

所以目前基本上,如果用户想在我网站上的帖子中添加评论,它会将他们带到另一个带有表单的页面。但是,我希望评论表单出现在实际的帖子详细信息页面上,这样用户就不必去另一个页面发表评论了。

到目前为止,我已经尝试添加一些上下文内容并将评论表单位置的 url 更改为post_detail.html,并将comment_form.html 的代码放在那里,但这不起作用。

这里是相关的views.py add_comment_to_post 视图

@login_required(login_url='/mainapp/user_login/')
def add_comment_to_post(request,pk):
    post = get_object_or_404(Post,pk=pk)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.author = request.user # add this line
            comment.save()
            return redirect('mainapp:post_detail',pk=post.pk)
            # remove `def form_valid`
    else:
        form = CommentForm()
    return render(request,'mainapp/comment_form.html',{'form':form})

这是PostDetailView 视图。

class PostDetailView(DetailView):
    model = Post

这是comment_form.html 代码

<form class="post-form" method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit" class="submitbtn">Comment</button>
</form>

这里是相关的urls.py 文件

path('post/<int:pk>/comment/', views.add_comment_to_post, name='add_comment_to_post'),

path('post/<int:pk>', views.PostDetailView.as_view(), name='post_detail'),

因此,目前,在执行我认为可行的解决方案时,我将 comment_form.html 的代码添加到 post_detail.html 文档中,但它只显示了Comment html 按钮。我如何才能将 CommentForm 与帖子详细信息页面放在同一页面上?

感谢您的帮助:)

【问题讨论】:

    标签: python django django-models django-forms django-views


    【解决方案1】:

    问题是当 Django 渲染 PostDetailView 时,context 字典没有 form 项(form 项仅在您的 add_comment_to_post 视图中可用,因为 Django 模板引擎无法从 context 字典中找到 form 项目,它没有呈现任何内容。

    您需要做的是更改您的PostDetailView 并将CommentForm 注入PostDetailView 的上下文中。这是一种方法:

    class PostDetailView(DetailView):
            model = Post
    
            def get_context_data(self, **kwargs):
                context = super().get_context_data(**kwargs)
                context['form'] = CommentForm() # Inject CommentForm
                return context
    

    您所做的实际上是覆盖默认的get_context_data,并将您的CommentForm() 作为context 的一部分注入,然后渲染它

    【讨论】:

    • 直到发表评论为止。当我按下评论按钮时,它把我带到了一个页面,上面写着This page isn't working。嘿,我能解决这个问题吗?我需要更改 urls.py 文件中的任何内容吗?
    • 我刚刚在表单中添加了一个 action=" ",这一切都很好,感谢您的帮助 :)
    【解决方案2】:

    你可以这样试试:

    class PostDetailView(DetailView):
            model = Post
    
            def get_context_data(self, **kwargs):
                context = super().get_context_data(**kwargs)
                context['comment_form'] = YourModelFormForComment()  # Your comment form
                return context
    

    在模板中

    {{comment_form.as_p}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-05
      • 2019-06-02
      • 2022-06-20
      • 2020-12-06
      相关资源
      最近更新 更多