TM.
TM.

Reputation: 111077

How to implement a "back" link on Django Templates?

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.

Upvotes: 45

Views: 51045

Answers (10)

Carlos Lopes
Carlos Lopes

Reputation: 43

In web development, there are various methods to implement a back button. I'd like to share two common approaches.

  1. Using JavaScript with onclick:
<button onclick="history.back()">Back</button>

This method utilizes JavaScript's history.back() function to navigate to the previous page in the browser history. It's a straightforward and effective solution.

  1. Using HTTP_REFERER like other comments above:
<a href="{{request.META.HTTP_REFERER}}">Back</a>

All this ways make store an history of pages, so if you open the page without historic and try back it don't will work, just reload the page. This work as intend.

Upvotes: 0

Markus
Markus

Reputation: 2572

All Javascript solutions mentioned here as well as the request.META.HTTP_REFERER solution sometimes work, but both break in the same scenario (and maybe others, too).

I usually have a Cancel button under a form that creates or changes an object. If the user submits the form once and server side validation fails, the user is presented the form again, containing the wrong data. Guess what, request.META.HTTP_REFERER now points to the URL that displays the form. You can press Cancel a thousand times and will never get back to where the initial edit/create link was.

The only solid solution I can think of is a bit involved, but works for me. If someone knows of a simpler solution, I'd be happy to hear from it. :-) The 'trick' is to pass the initial HTTP_REFERER into the form and use it from there. So when the form gets POSTed to, it passes the correct, initial referer along.

Here is how I do it:

I created a mixin class for forms that does most of the work:

from django import forms
from django.utils.http import url_has_allowed_host_and_scheme

class FormCancelLinkMixin(forms.Form):
    """ Mixin class that provides a proper Cancel button link. """
    cancel_link = forms.fields.CharField(widget=forms.HiddenInput())

    def __init__(self, *args, **kwargs):
        """
        Override to pop 'request' from kwargs.
        """
        self.request = kwargs.pop("request")
        initial = kwargs.pop("initial", {})
        # set initial value of 'cancel_link' to the referer
        initial["cancel_link"] = self.request.META.get("HTTP_REFERER", "")
        kwargs["initial"] = initial
        super().__init__(*args, **kwargs)

    def get_cancel_link(self):
        """
        Return correct URL for cancelling the form.

        If the form has been submitted, the HTTP_REFERER in request.meta points to
        the view that handles the form, not the view the user initially came from.
        In this case, we use the value of the 'cancel_link' field.

        Returns:
            A safe URL to go back to, should the user cancel the form.

        """
        if self.is_bound:
            url = self.cleaned_data["cancel_link"]
            # prevent open redirects
            if url_has_allowed_host_and_scheme(url, self.request.get_host()):
                return url

        # fallback to current referer, then root URL
        return self.request.META.get("HTTP_REFERER", "/")

The form that is used to edit/create the object (usually a ModelForm subclass) might look like this:

class SomeModelForm(FormCancelLinkMixin, forms.ModelForm):
    """ Form for creating some model instance. """

    class Meta:
        model = ModelClass
    # ...

The view must pass the current request to the form. For class based views, you can override get_form_kwargs():

class SomeModelCreateView(CreateView):
    model = SomeModelClass
    form_class = SomeModelForm

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs["request"] = self.request
        return kwargs

In the template that displays the form:

<form method="post">
  {% csrf token %}
  {{ form }}
  <input type="submit" value="Save">
  <a href="{{ form.get_cancel_link }}">Cancel</a>
</form>

Upvotes: 2

Kermit
Kermit

Reputation: 6012

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

Here |escape is used to get out of the " "string.

Upvotes: 16

Carlo Ledesma
Carlo Ledesma

Reputation: 446

For RESTful links where "Back" usually means going one level higher:

<a href="../"><input type="button" value="Back" class="btn btn-primary" /></a>

Upvotes: 3

mcwong
mcwong

Reputation: 783

Actually it's go(-1).

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

Upvotes: 58

Abdul Gaffar
Abdul Gaffar

Reputation: 390

Using client side solution would be the proper solution.

<a href="javascript:history.go(-1)" class="btn btn-default">Cancel</a>

Upvotes: 0

nivhab
nivhab

Reputation: 687

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

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

Upvotes: 3

Erasmo
Erasmo

Reputation: 94

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)

Upvotes: 0

Pegasus
Pegasus

Reputation: 849

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.

Upvotes: 51

Oli
Oli

Reputation: 239880

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.

Upvotes: 12

Related Questions