Django: How to return to previous URL
Question: Novice here who learned to develop a web app with python using Flask. Now I'm
trying to learn django 1.9 by redoing the same app with django. Right now I am
stuck at trying to get the current URL and pass it as an argument so that the
user can come back once the action on the next page is completed.

In Flask, to return to a previous URL, I would use the 'next' parameter and
the request.url to get the current url before changing page.

In the template you would find something like this:

    
    
    <a href="{{ url_for('.add_punchcard', id=user.id, next=request.url) }}">Buy punchcard :</a>
    

and in the view:

    
    
    redirect(request.args.get("next"))
    

I thought it would be about the same with django, but I cannot make it work. I
did find some suggestions, but they are for older django version(older than
1.5) and do not work anymore(and they are pretty convulsed as solutions goes!)

Right now, in my view I am using

    
    
    return redirect(next)
    

Note: The use of return redirect in django seems very recent itself if I judge
by solutions on the web that always seem to use return HttpResponse(..., so I
take it alot of changes happened lately in how to do things.

and in the template I have

    
    
    <a href="{% url 'main:buy_punchcard' member.id next={{ request.path }} %}">Buy punchcard</p>
    

but this actually return an error

> Could not parse the remainder: '{{' from '{{'

I did add the context_processors in settings.py

    
    
    TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.request',
    )
    

But this is only the last error in a very long streak of errors. Bottom line
is, I can't make it work.

As such, anyone could point me in the right direction as to what is the way to
do this in django 1.9? It look like a pretty basic function so I thought it
would be easier somehow.


Answer: If you want `next` to be included in the query string, then move it outside of
the `url` tag:

    
    
    <a href="{% url 'main:buy_punchcard' member.id %}?next={{ request.path }}">Buy punchcard</p>
    

In your view, you can fetch `next` from `request.GET`, and return the redirect
response using either `HttpResponseRedirect` or the `redirect` shortcut.

    
    
    from django.utils.http import is_safe_url
    
    next = request.GET.get('next', '/default/url/')
    # check that next is safe
    if not is_safe_url(next):
        next = '/default/url/'
    return redirect(next)
    

Note that **it might not be safe to redirect to a url fetched from the query
string**. For example, it could link to a different domain. Django has a
method
[`is_safe_url`](https://github.com/django/django/blob/2bdc9616f469c6b303bdc2711305ce9a1abbdcb6/django/contrib/auth/views.py)
that it uses to check next urls when logging in or out.

