当我的 Django 表单无法验证时,它会自动返回表单失败的页面,但我希望它转到页面上的 html 锚点。这是我的代码:
def detail(request, post_id):
p = get_object_or_404(Post, pk=post_id)
# get all the comments for the post
comments = p.comment_set.all().order_by('pub_date')
# to add a comment to the post
if request.method=='POST':
form = CommentForm(request.POST)
if form.is_valid():
c = Comment()
c.body = request.POST['body']
c.post = p
c.save()
return HttpResponseRedirect(reverse('journal.views.detail', kwargs={'post_id': post_id}) + "#comment-" + str(c.id))
else:
form = CommentForm()
return render(request, 'posts/detail.html', {'post': p, 'comments': comments, 'form': form})
该表单是博客文章底部的评论表单。当表单无效时,我希望它跳转到页面底部的评论表单的 html 锚点。现在它转到页面顶部,您必须向下滚动才能注意到有错误。
我尝试了一些不起作用的东西。请帮忙!