We are using the @login_required decorator so that users see a login page if they try to access a url for which they need to be authenticated.
We want to show a ‘cancel’ button on the login page, which should return the user to whichever page they were on when they tried to access the url (by clicking a link etc – we don’t need to deal with them manually entering the url).
At the moment our login.html looks for a request parameter ‘login_cancel_url’ and if present uses that (otherwise the home page).
However, this means we have to manually pass this parameter (set to the url of the current page) whenever we show a link or button that leads to an ‘authentication required’ url.
Is there a more elegant way to do this?
Thanks, Martin
Well you can try get the referrer header from the request but as far as I am aware, it’s browser dependent and is not very reliable so the way you are doing it is probably best. You could try make life easier by creating template tags to avoid having to rewrite the return URL manually.
You are easily able to get the current URL from django’s
requestobject on any page, so instead of setting it manually on the link, you could write a snippet of html:link_to_login.html
and use the
{% include "link_to_login.html"%}template tag.Alternatively, If the text needs to be different depending on the link you can instead create an inclusion template tag:
templatetags/extra_auth_tags.py
templates/extra_auth_tags/login_link.html
and then call it in your templates as
{% login_link text="Check you messages" %}. Be aware that keyword arguments for inclusion tags are only supported in the django dev version so you might need to write the template tag by hand.