Django-从View重定向到另一个域 [英] Django - Redirect to another domain from View

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

问题描述

我正在尝试从 mydomain.com 重定向到google.com。
在stackoverflow上有几个答案,假设以下情况有效:

I'm trying to redirect from mydomain.com to google.com. There are a couple of answers on stackoverflow that asume the following is working:

return HttpResponseRedirect('google.com')

return redirect('google.com')

但不是。这只是将页面重定向到其自身,并附加了 google.com 部分,因此它的显示如下:

But it doesn't it. This just redirects the page to itself and appends the google.com part so it comes out like this:

www.mydomain.com/google.com

抛出404错误当然。.
我的视图现在如下所示:

What throws a 404 of course.. My view now looks like the following:

class MyView(TemplateView):

    def get(self, request, *args, **kwargs):
        return HttpResponseRedirect('google.com')

有人可以给我关于我做错事情的见解吗?

Can anyone give me insights in what I'm doing wrong?

推荐答案

他们从某种意义上来说,答案是正确的:您进行了重定向。但是现在Web浏览器需要执行重定向。

They answers are in some sense correct: you do a redirect. But now the web browser needs to perform the redirect.

通常不以两个连续斜杠作为前缀的路径被假定为 local :这表示它停留在同一个域中。

Usually paths that are not prepended with two consecutive slashes are assumed to be local: so that means it stays at the same domain.

如果您想转到另一个域,则需要添加一个协议或至少两个连续的斜杠(以便重新使用 old 协议):

In case you want to go to another domain, you need to add a protocol, or at least two consecutive slashes (such that the old protocol is reused):

return HttpResponseRedirect('https://google.com')  # use https

或:

return HttpResponseRedirect('//google.com')  # "protocol relative" URL

毕竟,您只向浏览器返回重定向答案。浏览器可以决定不遵循重定向(某些浏览器可以这样做),也可以按照他们喜欢的任何方式对其进行解释(尽管这意味着浏览器并没有真正做到我们可以预期的做)。我们不能强迫浏览器遵循重定向。

After all you only return a redirect answer to the browser. The browser can decide not to follow the redirect (some browsers do), or can interpret it in any way they like (although that means that the browser does not really does what we can expect it to do). We can not force a browser to follow the redirect.

这篇关于Django-从View重定向到另一个域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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