问题
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