Reputation: 15620
I have seen this question where you can redirect to the previous page using:
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
but is there a way to also keep the scroll position that it was at? The above reloads the page afresh.
Upvotes: 4
Views: 3548
Reputation: 1
I don't know if this is what you are looking for but you can try:
<a href="javascript:history.back()">Back</a>
Hope this helps!
Upvotes: -1
Reputation: 15620
After some back and forth, this is what I came up with (with help from this answer):
from django.http import HttpResponse
def myview (request):
..
..
return HttpResponse('<script>history.back();</script>')
Also, keep in mind that history.back()
does not 'reload' the page. To also reload the page, we have to use location.reload()
which also keeps the scroll position but we have to use it in a clever way so as not to let it go into an infinite loop. So this is what I did to get around it (as mentioned in this clever answer)
<input type="hidden" id="refreshed" value="false">
<script type="text/javascript">
$(window).load(function(){
if ($('#refreshed').val() == "false") {
$('#refreshed').val("true");
}
else {
$('#refreshed').val("false");
location.reload();
}
});
</script>
Note: The above is using a hidden input field because the state of the input field would retain when 'back' is invoked.
All that said, you may want to consider doing an Ajax call if that works better in your use case instead of doing the above.
Upvotes: 8