Question

I'm tooling around with Django and I'm wondering if there is a simple way to create a "back" link to the previous page using the template system.

I figure that in the worst case I can get this information from the request object in the view function, and pass it along to the template rendering method, but I'm hoping I can avoid all this boilerplate code somehow.

I've checked the Django template docs and I haven't seen anything that mentions this explicitly.

Was it helpful?

Solution

Well you can enable:

'django.core.context_processors.request',

in your settings.TEMPLATE_CONTEXT_PROCESSORS block and hook out the referrer but that's a bit nauseating and could break all over the place.

Most places where you'd want this (eg the edit post page on SO) you have a real object to hook on to (in that example, the post) so you can easily work out what the proper previous page should be.

OTHER TIPS

Actually it's go(-1).

<input type=button value="Previous Page" onClick="javascript:history.go(-1);">

This solution worked out for me:

<a href="{{request.META.HTTP_REFERER}}">Go back</a>

But that's previously adding 'django.core.context_processors.request', to TEMPLATE_CONTEXT_PROCESSORS in your project's settings.

<a href="{{request.META.HTTP_REFERER|escape}}">Back</a>

|escape to get out of the "" stringage

For a 'back' button in change forms for Django admin what I end up doing is a custom template filter to parse and decode the 'preserved_filters' variable in the template. I placed the following on a customized templates/admin/submit_line.html file:

<a href="../{% if original}../{% endif %}?{{ preserved_filters | decode_filter }}">
    {% trans "Back" %}
</a>

And then created a custom template filter:

from urllib.parse import unquote
from django import template

def decode_filter(variable):
    if variable.startswith('_changelist_filters='):
        return unquote(variable[20:])
    return variable

register = template.Library()
register.filter('decode_filter', decode_filter)

You can always use the client side option which is very simple:

<a href="javascript:history.go(1)">Back</a>

Using client side solution would be the proper solution.

<a href="javascript:history.go(-1)" class="btn btn-default">Cancel</a>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top