django redirect()带参数 [英] django redirect() with parameters

查看:2675
本文介绍了django redirect()带参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已经有几个类似的问题已经出现了,但是在花费长时间后我找不到我的问题的答案。

There have been several similar questions asked already but I couldn't find answer to my problem after spending loong hours.

在下面的代码中,当我重定向到另一个view来自myView参数username,它可以正常工作。但是,我需要在此重定向中包含range参数,因为重定向后使用的模板需要范围。每当我尝试做,我会收到几个错误,如:

In the code below when I redirect to "anotherView" from "myView" with parameter "username", it works fine as expected. But I need to include "range" parameter in this redirect too as this "range" is required for the template used after redirection. Whenever I try to do, I get several errors like:

- 不要混合* args和** kwargs在调用reverse()

-- "Don't mix *args and **kwargs in call to reverse()"

有没有办法按照我想要的方式进行管理?

Is there a way to manage this the way I want?

   def myView(request):
      if request.user.is_authenticated():
        if request.method == 'POST':
                #my code comes here
                ....
                return redirect('anotherView', username=request.user.username, {"range": range(int(layout))})



   def anotherView(request,username):
      if request.user.is_authenticated():
        #my code comes here
          ....
          return redirect(something)


推荐答案

redirect 只是一个包装在 HttpResponseRedirect 下,自动调用 reverse ,以创建要重定向到的URL。因此,您传递给它的参数不是任意的,它们必须相同,您将传递给 reverse ,具体而言只是创建URL所需的参数。

redirect is merely a wrapper around HttpResponseRedirect that automatically calls reverse for you to create the URL to redirect to. As a result, the parameters you pass to it, aren't arbitrary, they must be same you would pass to reverse and, specifically, only those required to create the URL.

许多人似乎有麻烦的理解,数据不能只是被任意传递给视图。 HTTP是无状态协议:每个请求都存在于它自己的上,就好像用户从未访问过该网站的任何其他页面一样。创建会议的概念是为了向一个凝聚力单位(如网站)提供状态感。使用会话,数据以某种形式的持久存储和密钥存储,以查找向客户端(通常为用户的浏览器)提供的数据。在下一页加载中,客户端将密钥发送回服务器,服务器使用它来查找数据以显示状态。

Many people seem to have troubles understanding that data can't just be arbitrarily passed to a view. HTTP is a stateless protocol: each request exists on it's own, as if user had never been to any other page of the site. The concept of a session was created to provide a sense of "state" to a cohesive unit such as a site. With sessions, data is stored in some form of persistent storage and a "key" to look up that data is given to the client (typically the user's browser). On the next page load, the client sends the key back to the server, and the server uses it to look up the data to give the appearance of state.

作为结果,如果您需要从另一个视图中获取数据,则需要将其添加到会话中,执行重定向,然后从下一个视图中查看会话中的数据。

As a result, if you need data from one view available in another, you need to add it to the session, do your redirect, and look up the data in the session from the next view.

这篇关于django redirect()带参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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