Django 重定向到上一个视图 [英] Django Redirect to previous view

查看:25
本文介绍了Django 重定向到上一个视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在页面 x 和页面 y 上有一个按钮重定向到页面 z.在第 z 页,我有一个需要填写的表格.保存后,我想重定向到页面 x 或 y(无论我最初在哪个页面).

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?

有什么想法吗?

谢谢!

推荐答案

您可以使用 GET 参数来跟踪您从哪个页面到达页面 z.因此,当您正常到达第 z 页时,我们会记住我们来自哪个页面.当您处理第 z 页上的表单时,我们使用之前保存的信息进行重定向.所以:

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:

页面 y 上的按钮/链接应包含一个参数,其值为当前 URL:

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>

然后在 page_z 的视图中,您可以将其传递给模板:

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) })

并在您的表单模板中:

<form action="{% if from %}?next={{ from }}{% endif %}" />
...

所以现在表单 - 当提交时 - 将传递一个 next 参数,该参数指示表单成功提交后返回的位置.我们需要修改视图来执行此操作:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆