Django重定向到以前的视图 [英] Django Redirect to previous view
问题描述
我在页面x和页面y上有一个按钮,重定向到页面z。
在页面z上,我有一个需要填写的表单。保存后,我想重定向到页面x或y(最初是我最初的)。
通常,在视图中使用redirect,并指定您要重定向到的页面。但是在这样的情况下你会做什么?
任何想法?
谢谢!
您可以使用GET参数来跟踪你到达哪个页面到页面z。所以当你正常到达页面z时,我们记得从哪个页面来。当您处理第z页上的表单时,我们会使用以前保存的信息进行重定向。所以:
第y页上的按钮/链接应包含一个参数,其值为当前URL:
< a href =/ page_z /?from = {{request.path | urlencode}}/>转到表单< / a>
然后在page_z的视图中,您可以将其传递给模板:
def page_z_view(self,request):
...
return render_to_response('mytemplate.html',{'from':request。 GET.get('from',None)})
和您的表单模板:
< form action ={%if from%}?next = {{from}} {%endif%}/>
...
所以现在表单 - 提交时会传递一个 next
参数,指示表单成功提交后的哪里返回。我们需要恢复视图来执行此操作:
def page_z_view(self,request):
/ pre>
...
如果request.method =='POST':
#所有的表单填充
next = request.GET.get('next',None)
如果下一个:
return redirect(next)
return render_to_response('mytemplate.html',{'from':request.GET.get('from',None)}
I have a button on page x and page y that redirects to page z. On page z, I have a form that needs filling out. Upon saving, I want to redirect to page x or y (whichever one I was on initially).
Normally, you use "redirect" in the view, and specify the page you want to redirect to. But what would you do in a case like this?
Any ideas?
Thanks!
解决方案You can use GET parameters to track from which page you arrived to page z. So when you are arriving normally to page z we remember from which page we came. When you are processing the form on page z, we use that previously saved information to redirect. So:
The button/link on page y should include a parameter whose value is the current URL:
<a href="/page_z/?from={{ request.path|urlencode }}" />go to form</a>
Then in page_z's view you can pass this onto the template:
def page_z_view(self, request): ... return render_to_response('mytemplate.html', { 'from' : request.GET.get('from', None) })
and in your form template:
<form action="{% if from %}?next={{ from }}{% endif %}" /> ...
So now the form - when submitted - will pass on a
next
parameter that indicates where to return to once the form is successfully submitted. We need to revist the view to perform this:def page_z_view(self, request): ... if request.method == 'POST': # Do all the form stuff next = request.GET.get('next', None) if next: return redirect(next) return render_to_response('mytemplate.html', { 'from' : request.GET.get('from', None)}
这篇关于Django重定向到以前的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!