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>
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.
- [Django]-AttributeError: 'QuerySet' object has no attribute 'add'
- [Django]-How can I fix PostgreSQL canceling statement error on Google SQL?
- [Django]-Django : authenticate() is not working for users created by register page, but working for those users who were created by admin
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).
- [Django]-Djangocms-installer not asking setup questions
- [Django]-Django cors headers and server error
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.
- [Django]-PlaceholderAdmin throws <lambda>() takes exactly 1 argument (2 given)
- [Django]-Django Rest Framework 3.7.7 does not handle Null/None ForeignKey values
- [Django]-Mock.assert_has_calls() not working as expected
- [Django]-Cannot urlencode() after storing QueryDict in session
- [Django]-Django ValueError: 'dtedeclared with a lazy reference to …..' when changed Model Name
Source:stackexchange.com