Pass window.location to Flask url_for

I am using python. On my page, when an anonymous user goes to the login page, I want to pass the variable to the backend so that it indicates where the user is coming from (send the URL).

So, when the user clicks on this binding:

<a href="{{ url_for('account.signin') }}">Sign in</a>

I want to send the current URL of the page where the user is located.

<script>
 var current_url = window.location.href;
<script>

I decided to send it like this:

<a href="{{ url_for('account.signin', current_url="window.location.href") }}">Sign in</a>

But I can not use javascript code inside url_for or how to pass it?

+4
source share
3 answers

Use request.pathto get the path when rendering the template.

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

Assuming you are using Django.

, :

from django.http import HttpResponseRedirect

def foo(request, *a, **kw):
    # sign in user
    return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

JQuery:

.

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

URL.

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

: url/for/signin?next=prev/location

:

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

, request , headers, , Docs:

headers

, .

HTTP_Referer, :

HTTP- ( referrer 1) - HTTP , - ( URI IRI), . referrer, - , .

Finally, you can access it from flask, since you would access any element of the dictionary:

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

All Articles