Skip to content Skip to sidebar Skip to footer

Pass Window.location To Flask Url_for

I'm using python.On my page when an anonymous user goes to the sign in page, I want to pass a variable to the backend so it indicates where the user is coming from ( send the URL).

Solution 1:

Use request.path to get the path while rendering the template.

<ahref="{{ url_for('account.signin') }}?next={{ request.path }}">Sign in</a>

Solution 2:

Assuming you're using Django.

In your view you can return the previous location that the User can from:

from django.http import HttpResponseRedirect

deffoo(request, *a, **kw):
    # sign in userreturn HttpResponseRedirect(request.META.get('HTTP_REFERER'))

Or with Jquery:

Add an ID to the link.

<a href="{{ url_for('account.signin') }}"id="signin">

Then add the next parameter and redirect the browser to the new url.

$("#signin").click(function(e){
    e.preventDefault()
    window.location = $(this).href + "?next=" + window.location.href;
}

should produce something like: url/for/signin?next=prev/location

In your view you can access that next variable like so:

def foo(request, *a, **kw):
    next_url = request.GET["next"]

Solution 3:

I think you should use the request object at its best, since it does provide a headers dictionary which has all request headers, quoting from flask's Docs:

headers

The incoming request headers as a dictionary like object.

Now, one of the headers elements is the HTTP_Referer, which is :

The HTTP referer (originally a misspelling of referrer1) is an HTTP header field that identifies the address of the webpage (i.e. the URI or IRI) that linked to the resource being requested. By checking the referrer, the new webpage can see where the request originated.

Finally, you can access it from flask as you would access any dictionary item:

>>>print('Referer is {}'.format(request.headers.get('Referer')))

Solution 4:

You can use request.path to get the current URL path (you can also use request.full_path which includes the query string part of the current URL path), but no need to construct the query string by yourself, just pass it to current_url.

Any keyword parameters pass to url_for that isn't a URL variable will become a query parameter automatically:

<ahref="{{ url_for('account.signin', current_url=request.path) }}">Sign in</a>

Post a Comment for "Pass Window.location To Flask Url_for"