问题
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).
So when the user clicks on this anchor link:
<a href="{{ url_for('account.signin') }}">Sign in</a>
I want to send current URL of the page where the user is currently.
<script>
var current_url = window.location.href;
<script>
I thought to send it like this:
<a href="{{ url_for('account.signin', current_url="window.location.href") }}">Sign in</a>
But I can't use javascript code inside url_for or how can I pass it?
回答1:
Use request.path to get the path while rendering the template.
<a href="{{ url_for('account.signin') }}?next={{ request.path }}">Sign in</a>
回答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
def foo(request, *a, **kw):
# sign in user
return 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"]
回答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:
headersThe 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')))
回答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:
<a href="{{ url_for('account.signin', current_url=request.path) }}">Sign in</a>
来源:https://stackoverflow.com/questions/37862640/pass-window-location-to-flask-url-for