[Django]-How to jump to anchor with invalid Django form?

3👍

I think that is fair enough:

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

1👍

One approach is to pass an extra key-value pair in the dict to contain the anchor name, and use JavaScript in the template to jump to it if needed.

Python side:

// ...
return render(request,
              'post/detail.html',
              {
                  // ...
                  'anchor': 'comment'
              })

The template:

function goToOnLoadAnchor()
{
    window.location.hash('{{ anchor }}');   // Or something with the same effect
}

{% ... %}
<body onload="goToOnLoadAnchor">
{% ... %}

You can also take advantage of custom template tags to add more flexibility.

0👍

CBV & jQuery

FormView

def form_invalid(self, form):
    return self.render_to_response(self.get_context_data(form=form, anchor='my-form'))

template

<form ... id='my-form'> ... </form>
<script>
    $(function () {
        {% if anchor %}
            $(document.body).animate({
                'scrollTop':   $('#{{ anchor }}').offset().top
            }, 2000);
        {% endif %}
    });
</script>

Uses jQuery for scrolling (instead of jumping).

0👍

With Vanilla JavaScript:

{% if form.is_bound %}
<script>
  document.addEventListener("DOMContentLoaded", function () {
    document.getElementById("your_id").scrollIntoView();
  });
</script>
{% endif %}

It works well with the addEventListener("DOMContentLoaded") listener. Otherwise it can give some weird results.

Leave a comment