views:

1683

answers:

3

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.

+6  A: 

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.

Oli
This is good info, and I stumbled onto "Model.get_absolute_url" in the docs after reading this. This actually solves the problem in my case, but I'm still curious the best course of action if you didn't have an object to point to.
TM
Really depends on the circumstance. If there is some way of working out which page "should" be the previous page, I'd go that way.. But some times that's not possible and referrer checking might be your only option (other than letting users use their back button).
Oli
I once went down the path of trying to do this via session variables, but that was a mistake; brittle and broke all the time. Your choices are the ones Oli mentioned, or else using JavaScript to click the Back button for them.
Carl Meyer
A: 

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

<A HREF="javascript:history.go(1)">
nivhab
I really hate such links. Firstly, they doesn't work when you come to a page from a saved link/another site. Secondly, I enable Javascript only for trusted sites (using NoScript firefox extension).There're other reasons, but comment space is limited.
Eugene Morozov
Ugly, but valid answer.
muhuk
It's not the best coding ever I agree. But the high advantage is ultra simple and it works. It would also work if you come from a different site as it using the browsers BACK functionality regardless where you came from.
nivhab
A: 

actually it's go(-1)

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

mcwong
Responses to other answers belong in the comments not in a new answer.
TM
@TM: this is a correct answer, so it's fine as its own.
Wahnfrieden