I would like to return to a particular web page location (jump to in-page anchor) after reading the view. In other words, in views.py, I would like to do something like:
context={'form':my_form}
return render(request, 'my_app/my_page.html/#my_anchor', context)
However, I need a file path and not an url.
I am aware I can do this with 'redirect' (Django redirect() with anchor (#) parameters) but I need to return the context form. Any ideas?
It doesn't make sense to include the anchor in the template. The template is the name of the template file on the disk that is being rendered, it is completely separate from the url.
You could add your anchor to the template context.
context['anchor'] = 'my_anchor'
return render(request, 'my_app/my_page.html, context)
Then in your template, you can change the location to the anchor using javascript. Assuming you are using jQuery, you could do:
{% if anchor %}
<script type='text/javascript'>
$(document).ready(function(){
window.location = '#{{ anchor }}'
});
</script>
{% endif %}
I would be wary of doing this if the anchor comes from user input. You don't want a malicious user to be able to redirect you to a different domain. I think that hardcoding '#' in the template should prevent the browser being redirected to a different domain, but I am not certain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With