python - 如何使用无效的 Django 表单跳转到 anchor ?

标签 python html django django-forms django-templates

当我的 Django 表单验证失败时,它会自动返回到表单失败的页面,但我希望它转到页面上的 html anchor 。这是我的代码:


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 anchor 。现在它转到页面顶部,您必须向下滚动才能注意到有错误。

我尝试了一些没有用的东西。请帮忙!

最佳答案

我认为这很公平:

  <script>
    function goToId() {
      if (!window.location.hash) window.location = window.location + '#your-id';
    }
    {% if form.is_bound %}
      $(window).on("load", goToId);
    {% endif %}
  </script>

关于python - 如何使用无效的 Django 表单跳转到 anchor ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13774318/

相关文章:

python - python列表理解中的冗余计算?

Python 列表/字典与 numpy 数组 : performance vs. 内存控制

Python - 如何提高小数的准确性?

html - 将标题元素与图像对齐

python无法导入opencv因为找不到libjpeg.8.dylib

javascript - 静态网站中的表格分页问题

html - 如何使用 CSS 添加子子菜单

django - 如何组合两个模型并在管理部分只制作一个表格?

python - "Symbol not found: __cg_jpeg_resync_to_restart"与 djangostack

Django i18n 用 html 翻译文本