Pass the redirect URL in a next
URL param. Like so:
<!-- In homepage template -->
<a href="{% url 'link-to-like-view' %}?next=/home/">Like</a>
<!-- in Detail template -->
<a href="{% url 'link-to-like-view' %}?next=/detail/">Like</a>
or simply:
<a href="{% url 'link-to-like-view' %}?next={{ request.path }}">Like</a>
To always pass the current URL as the redirect URL.
And then in your LikeView
:
def LikeView(request, slug):
...
next = request.GET.get("next", None)
if next and next != '':
return HttpResponseRedirect(redirect_to=next)
# Then have a default redirect URL in case `next` wasn't passed in URL (Home for Example):
return HttpResponseRedirect(redirect_to="/home")
As mentioned in the Django Docs, this isn't safe (for most apps), so you have to check if URL is safe then redirect to next
otherwise just return a default safe in-app URL.
Read on the url_has_allowed_host_and_scheme
function to check if URL is safe on this Docs page
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…