所以目前基本上,如果用户想在我网站上的帖子中添加评论,它会将他们带到另一个页面,上面有表单。但是,我希望评论表单出现在实际的帖子详细信息页面上,这样用户就不必去另一个页面发表评论了。
到目前为止,我已经尝试添加一些上下文内容并将评论表单位置的 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 文档中,但它只显示了Commenthtml 按钮。我如何才能将 CommentForm 与帖子详细信息页面放在同一页面上?
繁花如伊
尚方宝剑之说
慕的地8271018
随时随地看视频慕课网APP
相关分类