Django - Redirect to another domain from View

你离开我真会死。 提交于 2020-01-05 07:05:14

问题


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

or

return redirect('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

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?


回答1:


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

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

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

or:

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.



来源:https://stackoverflow.com/questions/50372949/django-redirect-to-another-domain-from-view

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