Django: How to return to previous URL

假装没事ソ 提交于 2019-12-12 09:47:08

问题


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.


回答1:


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 that it uses to check next urls when logging in or out.




回答2:


You don't need {{ }} there, just:

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


来源:https://stackoverflow.com/questions/35894990/django-how-to-return-to-previous-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!